0

Consider my code below:

    System.out.println("Insert your inventory");
    for (int i = 0; i<20;i++) {
       System.out.print(i+1+".");
       if (inventory[i] == "N" || inventory[i]=="n") {
          break;
       }
       inventory[i] = s.nextLine();     
    }

How can I exit from this loop if the user enters 'N' or 'n'?

Rann Lifshitz
  • 4,040
  • 4
  • 22
  • 42

2 Answers2

1

You're comparing string with == operator. It does not yield correct result because your constant string "N" and your input "N" do not have same reference/pointer.

You have to use equals() to guarantee the correct compare result between strings.

Replace

if (inventory[i] == "N" || inventory[i]=="n") 

With

if (inventory[i].equals("N") || inventory[i].equals("n")) 
Mạnh Quyết Nguyễn
  • 17,677
  • 1
  • 23
  • 51
0

You should compare your String variables with the .equals() method instead of the == operator.

An explanation about why this is important can be found here on StackOverflow.

Rann Lifshitz
  • 4,040
  • 4
  • 22
  • 42
Kaushal28
  • 5,377
  • 5
  • 41
  • 72