1

我试图一个接一个地扫描字符串,有些可能包含空格。由于我的代码功能目前只有当您输入的每个字符串都是一个单词时它才会起作用。无论行中是否有空格,扫描连续文本行的正确方法是什么。

System.out.print("Enter your first name: ");
                fName = scan.next();

                System.out.print("Enter your last name: ");
                lName = scan.next();

                System.out.print("Enter your street and house number: ");
                address = scan.next();

                System.out.print("Enter your city: ");
                city = scan.next();

                System.out.print("Enter your state: ");
                state = scan.next();

                System.out.print("Enter your telephone number (no spaces): ");
                teleNum = scan.next();

                System.out.print("Enter your zip code: ");
                zip = scan.next();
4

1 回答 1

1
    String[] prompts = {
        "Enter your city: ",
        "Enter your state: ",
    };

    Scanner scanner = new Scanner(System.in);
    String line = "";
    for (String prompt : prompts) {
        System.out.println(prompt);
        if (scanner.hasNextLine()) { 
            line += scanner.nextLine();
        }
    }

    System.out.println(line);
于 2013-02-07T05:22:44.300 回答