运行时错误java scanner不接受中间有空格的两个单词
我正在尝试创建一个简单的项目,它将询问用户true或false,如果为true,那么扫描器将继续在arraylist中存储类别名称。 它可以正常工作,直到你在类别名称“first second”中输入两个带空格的单词。例如,出于某种原因,它跳入条件true或false,检查我是否输入了另一个单词而不是true或false,然后执行catch子句。 我试过使用两种扫描仪。next或nextline,nextline只需跳转到true或false,而无需询问类别名称。 请帮忙。 非常感谢你
public class MainClass {
public static boolean check = false;
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
Categories c = new Categories();
System.out.println("Please enter true if you want to add a category \n or false if not");
try {
check = in.nextBoolean();
} catch (InputMismatchException e) {
System.out.println("Sorry you must put true or false!!!");
System.exit(0);
}
while (check) {
System.out.println("Please enter category name");
c.category.add(in.next().toString());
System.out.println("do you want to add more true or false");
try {
check = in.nextBoolean();
} catch (InputMismatchException e) {
System.out.println("Sorry you must put true or false!!!");
System.exit(0);
}
}
System.out.println("Thank you all categories are added");
System.out.println(c.category);
}
}
# 1 楼答案
您可以使用围绕BufferedReader的InputStreamReader:
# 2 楼答案
改变
到
改变
致: