gpt4 book ai didi

java扫描仪不接受两个单词之间有空格

转载 作者:行者123 更新时间:2023-11-30 03:26:05 25 4
gpt4 key购买 nike

我正在尝试创建一个简单的项目,它将询问用户是真是假,如果是,那么扫描仪将继续将类别名称存储在数组列表中。它工作正常,直到您在类别名称“第一秒”中输入两个带有空格的单词,例如由于某种原因它会跳转到条件 true 或 false 并检查我是否输入了除 true 或 false 之外的另一个单词并执行 catch 子句。我尝试过使用 Scanner.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);





}

}

最佳答案

改变

check = in.nextBoolean();

check = in.nextBoolean();
in.nextLine(); // to swallow end of line token

并改变

c.category.add(in.next().toString());

至:

c.category.add(in.nextLine()); // to get the whole line

关于java扫描仪不接受两个单词之间有空格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30178127/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com