我最近遇到了这个令人沮丧的问题,扫描程序完全忽略了System.in输入流中的一些输入。这是一个例子:
Do you want a cookie? Yes or no.
现在,我输入是:
yes
结果:
Cookie for you!
现在,如果我说不:
no
no
结果:
No Cookie for you.
得到它?如果我说是,那就接受它。如果我说不,我必须输入2次。
如果你真的需要一些代码。其中一些是:)
public static void main(String[] paramArgs){
MainEW sMain = new MainEW();
Scanner s = sMain.scanner;
System.out.println("Enter a file path.");
System.out.println("Example: /Users/Some_User/Desktop/Some_Folder");
String defPath = s.next();
System.out.println("Enter a name for the file.");
String defName = s.next() + ".txt";
System.out.println("Now, enter what you want to write to the file.");
s.nextLine();
String defText = s.nextLine();
System.out.println("Do you want to create a new file? Yes or No");
if (s.next().equalsIgnoreCase("yes")) {
WriterEW writer = new WriterEW(defPath, defName, defText, true);
return;
} else if (s.next().equalsIgnoreCase("no")) {
WriterEW writer = new WriterEW(defPath, defName, defText, false);
return;
} else {
System.out.println("Invalid input.");
}
}
谢谢:)
答案 0 :(得分:6)
当您输入“no”时,else if
块会再次调用next()
,要求提供更多输入。
不是在每种情况下都致电s.next()
,而是在开始if
条件之前只调用一次。
String response = s.next();
if(response.equalsIgnoreCase("yes")){
WriterEW writer = new WriterEW(defPath, defName, defText, true);
return;
}else if(response.equalsIgnoreCase("no")){