无法将双精度转换为布尔值

Cannot convert double to boolean

抱歉,如果这让您感到困惑,我对编码还是个新手。我试图提示用户输入一个数字并显示输入的数字是否在数组中。似乎真的找不到答案。

import java.util.Scanner;

public class Arrays3 {
    public static void main(String[] args) {
        double[] don = { 2.1, 3.2, 4.5, 6.0, 4.5, 1.5, 6.0, 7.0, 6.0, 9.0 };
        Scanner kbd = new Scanner(System.in);

        System.out.println("Enter a number");
        double num = kbd.nextDouble();
        if (num = don.length) {
            System.out.println("The number you entered is in the Array");
        } else {
            System.out.println("The number you entered is not in the Array");
        }

    }
}

你用过

if (num = don.length) {

你应该使用的地方

if (num == don.length) {

在第一种情况下,您将 don.length 分配给 num,返回新分配的值。

此外,您的代码不会检查读取的数字是否在您的数组中。要检查这一点,您可以使用类似的东西:

boolean found = false;
for(int i = 0; i < don.length; i++) {
    if(num == don[i]) {
        found = true;
        break; // Stop the loop as a match has already been found.
    }
}
if(found) {
    System.out.println("The number you entered is in the Array");
} else {
    System.out.println("The number you entered is not in the Array");
}

如果您要在数据数组中搜索输入值,您可能需要遍历数组并检查输入是否与数组中的任何值匹配。

public static void main(String[] args) {
    double[] don = { 2.1, 3.2, 4.5, 6.0, 4.5, 1.5, 6.0, 7.0, 6.0, 9.0 };
    Scanner kbd = new Scanner(System.in);

    System.out.println("Enter a number");
    double num = kbd.nextDouble();
    boolean isFound = false;

    for(int i = 0; i < don.length; i++) {
        if (num == don[i]) {
            isFound = true;
        }
    }

    if (isFound) {
        System.out.println("The number you entered is in the Array");
    } else {
        System.out.println("The number you entered is not in the Array");
    }
}

检查元素是否存在于数组中的方法很少

  • 使用 for 循环
  • Java 8 流 API
  • Arrays.asList().contains()

这是检查您的输入(在本例中为 num)是否存在于给定数组 don 中的一种方法:

import java.util.Scanner;
import java.util.Arrays;

class Main {
  public static void main(String[] args) {
    double[] don = { 2.1, 3.2, 4.5, 6.0, 4.5, 1.5, 6.0, 7.0, 6.0, 9.0 };
    Scanner kbd = new Scanner(System.in);

    System.out.println("Enter a number");
    double num = kbd.nextDouble();
    boolean existsInArray = Arrays.stream(don).anyMatch(arrayNum -> arrayNum == num);

    if (existsInArray) {
      System.out.println("The number you entered is in the Array");
    } else {
      System.out.println("The number you entered is not in the Array");
    }
  }
}

existsInArray 变量使用 Java 8 Stream API,特别是 anyMatch() 方法,检查给定的输入(称为 num 这里),包含在数组 don 中。如果是这样,existsInArraytrue 否则 false.