0

我正在尝试使用 Scanner 对象来读取键盘输入(双类型数字)。程序可以编译,但它只能接受两个数字。下面是我的代码,请帮我找出原因。谢谢!

    public static void main(String[] args)
    {
        Scanner keyboard = new Scanner(System.in);
        ArrayList<String> container = new ArrayList<String>();
        double number = 0;

        System.out.println("Type in the polynomials in increasing powers:");

        while (!keyboard.nextLine().isEmpty())
        {           
//          number = keyboard.nextDouble();
            try {
                     number = keyboard.nextDouble();
            } catch(Exception e)              // throw exception if the user input is not of double type
            {
                System.out.println("Invalid input");
            }


            container.add("-" + number);

        }
4

1 回答 1

2

nextLine()方法调用

while (!keyboard.nextLine().isEmpty())

将消耗double您输入的第一个值。这个

number = keyboard.nextDouble();

然后将消耗第二个。

当循环再次迭代时,keyboard.nextLine()将消耗它将消耗的行尾字符trim()isEmpty()将因此返回true

如果要输入数字,请按回车键,然后继续输入数字,解决方案是将行读取为 aString并用于Double.parseDouble(String)获取double值。

否则,您也可以使用

while (keyboard.hasNextDouble()) {
    number = keyboard.nextDouble();
    System.out.println(number);
    ...
}

并在以空格分隔的单行输入您的数字

22.0 45.6 123.123123 -61.31 -

最后使用一个随机的非数字字符来告诉它输入完成。以上印刷品

22.0
45.6
123.123123
-61.31

并停止。

于 2013-09-13T20:52:33.583 回答