问题
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'?
回答1:
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.
回答2:
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"))
来源:https://stackoverflow.com/questions/50422088/exit-array-for-loop-java