java 扫描器不接受中间带有 space 的两个词

java scanner does not accept two words with space in between

我正在尝试创建一个简单的项目,它会询问用户是真还是假,如果是真,那么扫描器将继续将类别名称存储在数组列表中。 在类别名称 "first second" 中输入两个带有 space 的单词之前,它工作正常并执行 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);





}

}

您可以使用围绕 BufferedReader 的 InputStreamReader:

BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
reader.readLine(); // this will read two words

改变

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