Exit array for loop Java [duplicate]

半世苍凉 提交于 2019-12-13 04:22:47

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!