退出循环Java数组
问题描述:
在下面考虑我的代码:
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();
}
如果用户输入"N"或"n",如何退出此循环?
How can I exit from this loop if the user enters 'N' or 'n'?
答
您应该将String变量与.equals()
方法而不是==
运算符进行比较.
You should compare your String variables with the .equals()
method instead of the ==
operator.
有关为什么这很重要的解释可以在这里中找到在StackOverflow 上.
An explanation about why this is important can be found here on StackOverflow.