我只有几周的编码工作,所以我真的很新。这是一个简单的程序,可帮助用户定制新车。该程序对每个菜单使用不同的方法。每个非主要方法都会询问用户他们想要2种自定义汽车选项中的哪一种,然后该方法将成本发送回主要系统。每个非主要方法都使用与方法engineCost
相同的格式。我不知道为什么我的键盘输入仅在do while循环的第一次迭代中起作用。这是我在eclipse上被提示的错误:
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;
}
}
答案 0 :(得分:2)
这是因为循环中的行:application-a30bb6a9753337386468559f6f44286d58d74f88ddc710b5d5832a67b576d16a.css
。第一次迭代后,这将关闭keyboard.close();
。此后,您尝试调用Scanner
(从docs起),它将抛出:
nextInt()
-如果此扫描仪已关闭
仅在完全使用完资源后,才应关闭资源。
话虽如此,请不要关闭IllegalStateException
。一般规则是,如果您没有打开它,则不应关闭它。