while循环初始化但不循环java
我试图运行的循环将初始化,但不会在第一个循环后继续运行。由于我知道问题出在哪里,我拿出了大部分代码来修复这个循环。我做了第二个选择后,循环将不会运行。感谢您的任何帮助。while循环初始化但不循环java
public static void main(String[] args)
{
String number; // enter number
int stringLength = 0;
String selection = "y" ;
// Create a Scanner object to read input.
Scanner keyboard = new Scanner(System.in);
// PrintWriter outputFile = new PrintWriter("outDataFile.txt");
// outputFile.close();
while (selection == "y")
{
// Get the user's number.
System.out.print("Write your number ");
number = keyboard.nextLine();
System.out.print("y/Y to continue, any else to exit");
selection = keyboard.nextLine();
}
}
您应该使用equals
,而不是==
的字符串作为==
仅比较引用而不是对象中的数据,所以:
while (selection.equalsIgnoreCase("y"))
忽略大小写,因为您在邮件中有"y/Y to continue, any else to exit"
。
和更好的'equalsIgnoreCase()' – NwDev
@NwDx正确的,加上 –
修改您的条件:
while ("y".equalsIgnoreCase(selection.trim()))
它的更好,所以你比较实际的字,而不是他对象标识与equals比较字符串。修剪会删除错误添加
而且任何空白,这是更好地与左边的不断"y"
比较,以避免NullPointerException
此外,如在对方的回答进行了说明,该equalsIgnoreCase()
也很重要。
Scanner.nextLine()应该永远不会返回null,但你说得对,应该比较常数是更好的方法。 – NwDev
使用'=='来比较字符串并不符合您在Java中所期望的。参见[如何比较Java中的字符串?](http://stackoverflow.com/questions/513832/how-do-i-compare-strings-in-java)。 – Jesper