-2

I am trying to make my program so you can input a number then get an output on the basis that if the input is equal to the number in the array it will print: "Value 7 is found in the array". If the value is not in the array it should say "Value X was not found in the array".

I am only getting the output that the value was not found in the array. Where am I going wrong?

Here is my code for this:

public static void main(String[] args) {
        Scanner reader = new Scanner(System.in);
        
        int [] array = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
        
        System.out.print("Enter a number you would like to search for: ");
        int num = reader.nextInt();
        
        if (num == array[0]) 
        System.out.println("Value " + num + "is in the array.");
        else
        System.out.println("Value " + num + " was not found in the array"); 
}

Alex Sveshnikov
  • 4,214
  • 1
  • 10
  • 26
ideekaye
  • 13
  • 5
  • All you do is check if the first element of your array is equal to the input. – OH GOD SPIDERS Mar 17 '21 at 11:47
  • Ah I see, this was the only way I could get my if statement to work. I'm not able to do [0, 10]. How would I go about checking for the whole array? – ideekaye Mar 17 '21 at 11:49

1 Answers1

0

Your code is comparing the user's input with just the first element of the array, i.e. array[0]. What you need to do is to loop through the whole array and compare the number with every element of the array.

Alex Sveshnikov
  • 4,214
  • 1
  • 10
  • 26