我正在尝试运行的循环将会初始化,但在第一个循环之后将不会继续运行。因为我知道问题出在哪里,所以我拿出了大部分代码来修复循环。在我做了第二次选择之后,循环将不会运行。谢谢你的帮助。
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();
}
} 发布于 2016-07-07 15:37:56
修改您的条件:
while ("y".equalsIgnoreCase(selection.trim()))最好将String与equals进行比较,这样就可以比较实际的单词,而不是对象标识。修剪将删除由错误添加的任何空格
此外,最好与左侧的常量"y"进行比较,以避免出现NullPointerException
此外,正如在另一个答案中解释的那样,equalsIgnoreCase()也很重要。
发布于 2016-07-07 15:37:22
您应该对字符串使用equals而不是==,因为==只比较引用而不是对象内部的数据,因此:
while (selection.equalsIgnoreCase("y"))忽略大小写,因为您的邮件中包含"y/Y to continue, any else to exit"。
https://stackoverflow.com/questions/38239906
复制相似问题