我正在拼凑一个简单的 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();
}
}