1

我正在拼凑一个简单的 Java 程序来解释循环。我希望每个演示都在一个单独的函数中。现在,每个函数都可以正常工作,但只有在不调用另一个函数时。如果我同时调用两者,我会在运行时收到以下错误:

Please input a positive integer as the end value: 5
The summation is: 9
How many rows do you want your triangle to be?: Exception in thread "main" java.util.NoSuchElementException
at java.util.Scanner.throwFor(Unknown Source)
at java.util.Scanner.next(Unknown Source)
at java.util.Scanner.nextInt(Unknown Source)
at java.util.Scanner.nextInt(Unknown Source)
at loops.exercise2(loops.java:48)
at loops.main(loops.java:11)

代码:

import java.util.Scanner;

public class loops
{

public static void main( String args[] )
{
    exercise1();
    System.out.println();
    exercise2();
}

public static void exercise1()
{

    int limit;
    int i;
    int sum;

    Scanner keyboard = new Scanner(System.in);


    System.out.print ("Please input a positive integer as the end value: ");

    limit = keyboard.nextInt();

    i=1;
    sum = 0;

    while (i <= limit)
    {
        sum = sum + i;
        i = i + 2;          
    }

    System.out.print("The summation is: " + sum);

    keyboard.close();
}

public static void exercise2()
{
    int numRows, i, j;
    Scanner keyboard = new Scanner(System.in);

    System.out.print("How many rows do you want your triangle to be?: ");
    numRows = keyboard.nextInt();

    for(i=0; i<numRows; i++)
    {
        for(j=0; j<=i; j++)
        {
            System.out.print("*");              
        }
        System.out.println();
    }

    keyboard.close();
}

}

4

4 回答 4

3

发生这种情况是因为当您关闭 Scanner 时,它也会关闭输入流,在本例中为 System.in。当您尝试在 execise2 方法中实例化 Scanner 时,输入流将关闭。

看到这个SO帖子......

https://stackoverflow.com/a/13042296/1246574

于 2013-07-29T17:01:34.130 回答
1

制作一个全局扫描器,只启动一次,然后调用它的方法。

于 2013-07-29T17:00:26.723 回答
1

试试不打电话keyboard.close();

于 2013-07-29T17:00:41.300 回答
1

我的猜测是您的 Scanner 类相互干扰。 exercise1从标准中获取输入,然后在完成后关闭。然后exercise2还尝试从关闭的标准中获取输入。

我建议您只制作 1 个扫描仪并将其作为参数传递给练习 1 和练习 2,然后在两次调用后将其关闭。

于 2013-07-29T17:00:09.847 回答