Apologies if this is confusing, I’m still new to coding. I’m trying to prompt the user for a number and display if the number entered is or is not in the array. Can’t really seem to find an answer.
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");
}
}
}
>Solution :
If you are searching for the input value inside your data array, you may want to traverse the array and check if the input matches with any value inside 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");
}
}
There are few ways to check if the element exists in the array
- Using a for-loop
- Java 8 Stream API
- Arrays.asList().contains()