0

这应该是一个非常基本的程序,但我是 Java 新手。我希望能够使用 Scanner 将多个字符串输入到控制台中来检测它们。到目前为止,我已经能够正确输入部分,我希望程序以这样一种方式运行,即在输入空白而不是字符串时显示结果。奇怪的是,当我点击两次 return 时,我只能得到结果,但是,当有超过 4 个输入点击 return 一次时。我的计数器应该计算输入的“课程”数量并将它们显示在结果中,但它给出的读数不准确。

import java.util.Scanner;

public class Saturn
{

    static Scanner userInput = new Scanner(System.in);

    public static void main(String[] args)
    {

        System.out.println("For each course in your schedule, enter its building");
        System.out.println("code [One code per line ending with an empty line]");

        String input;
        int counter = 0;

        while (!(userInput.nextLine()).isEmpty())
        {
            input = userInput.nextLine();
            counter++;
        }


        System.out.println("Your schedule consits of " + counter + " courses");
    }
}
4

1 回答 1

2

你调用Scanner#nextLine了两次——一次在while循环表达式中,一次在循环体中。您可以inputwhile循环表达式中分配。此外,您可以使用Scanner#hasNextLine来防御NoSuchElementException发生:

while (userInput.hasNextLine() && 
        !(input = userInput.nextLine()).isEmpty()) {
   System.out.println("Course accepted: " + input);
   counter++;
}
于 2013-04-06T20:40:03.903 回答