我正在用一个简单的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();
}
}
答案 0 :(得分:3)
这种情况正在发生,因为当您关闭扫描程序时,它还会关闭输入流,在本例中为System.in。当您尝试在execise2方法中实例化扫描器时,输入流将被关闭。
见SO帖子......
答案 1 :(得分:1)
我的猜测是你的扫描仪课程互相干扰。 exercise1
从标准输入,然后在完成后关闭。然后exercise2
也会尝试从标准中获取输入。
我建议您只制作1个扫描仪并将其作为参数传递给exercise1和exercise2,然后在两次调用后将其关闭。
答案 2 :(得分:1)
创建一个全局扫描程序,并仅启动一次,然后调用其方法。
答案 3 :(得分:1)
尽量不要致电keyboard.close();