我在使用这行代码时遇到了困难。代码是计算一个互联网服务账单,其中套餐A每月花费9.95美元,10小时,额外花费2.00美元。套餐B每月花费13.95美元,20小时,额外费用为1.00美元。套餐C每月花费19.95美元。我放入小时后,我不断收到此错误java.util.NoSuchElementException。
以下是代码:
import java.util.Scanner;
public class InternetServiceProvider {
public static void main (String args[])
{
while (true)
{
printMonthlyBill(calculateBill(getHours(), menu()));
}
}
public static double getHours()
{
double hours;
Scanner inputHours = new Scanner (System.in);
System.out.print("Please enter the hours used: ");
hours = inputHours.nextDouble();
inputHours.close();
return hours;
}
public static int menu ()
{
int packageChoice;
Scanner userInput = new Scanner (System.in);
System.out.println("Which package have you obtain? (Please use A, B, or C)");
System.out.println("[1] Package A");
System.out.println("[2] Package B");
System.out.println("[3] Package C");
System.out.print("Please select your package: ");
packageChoice = userInput.nextInt();
userInput.close();
return packageChoice;
}
}
这是输入:
Please enter the hours used: 25
Which package have you obtain? (Please use A, B, or C)
[1] Package A
[2] Package B
[3] Package C
Please select your package: 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 InternetServiceProvider.menu(InternetServiceProvider.java:37)
at InternetServiceProvider.main(InternetServiceProvider.java:8)
答案 0 :(得分:-1)
您正在关闭System.in
。您应该在两种方法之间共享Scanner
,并在完成后关闭。
public static void main (String args[])
{
try(Scanner input = new Scanner (System.in)) {
while (true)
{
printMonthlyBill(calculateBill(getHours(input), menu(input)));
}
}
}
public static double getHours(Scanner input)
{
double hours;
System.out.print("Please enter the hours used: ");
hours = input.nextDouble();
return hours;
}
public static int menu (Scanner input)
{
int packageChoice;
System.out.println("Which package have you obtain? (Please use A, B, or C)");
System.out.println("[1] Package A");
System.out.println("[2] Package B");
System.out.println("[3] Package C");
System.out.print("Please select your package: ");
packageChoice = input.nextInt();
return packageChoice;
}