我有一个简单的程序,我只是提示输入一个项目,而 while 循环将继续询问,直到我输入单词“end”,然后它将结束程序。当我输入这样的单词时:
看起来不错,但是当我为一个项目输入 2 个单词时,我得到以下输出:
请注意,当我输入“绿色黄色”时,它提示我输入一个项目两次? 我不明白为什么要这样做?
import java.util.Scanner;
public class ToDoListapp {
public static void main(String[] args) /*throws IOException*/ {
// TODO Auto-generated method stub
Scanner sc = new Scanner(System.in);
System.out.println("Welome to your TodoList");
boolean keepAdd = true;
String item;
//file
//PrintWriter writeFile = new PrintWriter("TodoList.txt", "UTF-8");
// File file = new File("ToDo.txt");
// BufferedWriter writeTo = new BufferedWriter(new FileWriter(file));
while (keepAdd)
{
System.out.println("Enter an item: ");
item = sc.next();
if (item.equals("end"))
{
keepAdd = false;
}
// writeTo.write(item + "\n");
}
//writeTo.close();
}
}
最佳答案
Scanner 的默认行为是使用空格作为分隔符,用于将输入分解为标记。如果您只想使用换行符作为分隔符,请尝试显式设置分隔符。
Scanner sc = new Scanner(System.in);
sc.useDelimiter(System.getProperty("line.separator"));
System.out.println("Welome to your TodoList");
boolean keepAdd = true;
String item;
// The rest of your code
关于java - 为什么我的字符串不能正确输出我的值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23438545/