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");
}
}
}
CodePudding user response:
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()
CodePudding user response:
Here is one way of checking if your input, in this case num
, is present in the given array don
or not:
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");
}
}
}
The existsInArray
variable is using the Java 8 Stream API, and in particular the anyMatch()
method, to check if the given input (called num
here), is contained in the array don
. If so, existsInArray
is true
else false
.
CodePudding user response:
You've used
if (num = don.length) {
where you should have used
if (num == don.length) {
In the first case, you are assigning don.length
to num
, returning the newly assigned value.
Additionally, your code does not check whether the read number is in your array. To check for this, you could use something like:
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");
}