当我第二次按键盘输入时,我的 Do-While 循环中断



我只有几周的编码时间,所以我真的很新。这是一个简单的程序,可帮助用户定制新车。该程序对每个相应的菜单使用不同的方法。每个非主要方法都会询问用户他们想要 2 个定制汽车选项中的哪一个,然后该方法将成本发回给主车。每个非 main 方法都使用与方法engineCost相同的格式。我不明白为什么我的键盘输入仅在我的 do while 循环的第一次迭代期间起作用。这是我在日食时提示的错误:

Exception in thread "main" java.lang.IllegalStateException

我做了一些关于堆栈溢出的查找,我认为我没有足够的知识来正确搜索答案。任何帮助将不胜感激。

import java.util.Scanner;
public class Ch5HW {
public static void main(String[] args){
double baseCar = 14000;
double addCost = 0;
double ttlCost = 0;
int userOpt;
Scanner keyboard = new Scanner(System.in);
System.out.println("Basic Car includes: Silver color, 4 cilinder engine, Cooper Tires; cost: $14,000");
System.out.println("");
//this do-while loops until the user enters 4 to exit 
do{
System.out.println("Build Car Quote");
System.out.println("1. Engine");
System.out.println("2. Color");
System.out.println("3. Tires");
System.out.println("4. Exit");
System.out.print("Enter Option: ");
userOpt = 0;
// this keyboard input only works on the first iteration of the loop
userOpt = keyboard.nextInt();
System.out.println(userOpt);
//nested switch to determine userOpt
switch (userOpt)
{
case 1:
// calls the engineCost method
addCost = engineCost();
//adds the value received to a total value
ttlCost += addCost;
break;
case 2:
//calls the colorOpt method
addCost = colorOpt();
//adds the value received to a total value
ttlCost += addCost;
break;
case 3:
//calls the tireOpt method
addCost = tireOpt();
//adds the value received to a total value
ttlCost += addCost;
break;
}
//System.out.print(addCost + baseCar);
keyboard.close();
} 
while (userOpt !=4);
//once loop has finished the total of additional purchases is added to the base car price 
System.out.print("Total cost: " + (ttlCost + baseCar));
}
// this method has options for the engine
static double engineCost()
{
double engineCost = 0;
double addCost =0;
int engineOpt;
Scanner keyboard = new Scanner(System.in);
System.out.println("Engine Options: ");
System.out.println("1. 8 cylinder: $5000.00");
System.out.println("2. 6 cylinder: $3500.00");
System.out.println("3. Exit");
System.out.println("Enter Option: ");
engineOpt = keyboard.nextInt();
switch (engineOpt)
{
case 1:
engineCost = 5000.00;
addCost += engineCost;
break;
case 2:
engineCost = 3500.00;
addCost += engineCost;
break;  
case 3:
engineCost = 0;
addCost += engineCost;
}
keyboard.close();
return addCost; 
}
}

这是因为该行:keyboard.close();在您的循环中。这将在第一次迭代后关闭Scanner。在此之后,您尝试调用(从文档中(将抛出的nextInt()

IllegalStateException- 如果此扫描仪已关闭

只有在完全使用完资源,才应将其关闭。

话虽如此,不要关闭System.in.一般规则是,如果您没有打开它,则不应关闭它。

最新更新