mardi 23 février 2016

Java - both if-else statements being executed

I inserted an int (among other variables) into an arraylist. Now I need the user to insert an int and have it go through each arraylist object to see if there is a matching int. If it finds the user's input in the arraylist, it has them move on to enter their name.

When I enter the first int that was entered into the arraylist, it works just fine. But if I enter the second (or third, etc.) int that was entered into the arraylist, it executes the else statement and says "We can't find this number.", then it executes the if statement and proceeds to have the user input their name.

Example output (if 1 is the first integer I entered into the arraylist and 2 is the second one and 0 isn't in the arraylist at all):

Enter number from the list:
0
We can't find this number.
Enter number from the list:
1
Enter your name:
Fred
Hello!
Enter number from the list:
2
We can't find this number.
Enter your name:

I would like to fix this so it doesn't print "We can't find this number." when entering 2 (or subsequent int's found in the arraylist). Here is my code, and note that there is another class (SecondaryClass) with the method getNumber. Let me know if any typos cause it not to run, as the computer my file is on does not currently have internet so I transcribed it over to this one.

do{
boolean foundNumber = false;
boolean continueLoop = true;
System.out.println("Enter number from the list:");
numberFromList = console.nextInt();
console.nextLine();
    for (int a = 0; a < arrayList.size() && foundNumber == false; a++){
    SecondaryClass currNumber = arrayList.get(a);
      if (currNumber.getNumber() == numberFromList){
         foundNumber = true;
         i = arrayList.size();
         System.out.println("Enter your name:");
         yourName = console.nextLine();
         System.out.println("Hello!");
         continue = true;
      } else {
         foundNumber = false;
         System.out.println("We can't find this number.");
      }
    }
}while (continueLoop == true);

Aucun commentaire:

Enregistrer un commentaire