作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我才刚开始编码几周,所以我真的很新。这是一个简单的程序,可以帮助用户定制新车。该程序对每个菜单使用不同的方法。每个非主要方法都会询问用户他们想要 2 个定制汽车选项中的哪一个,然后该方法将成本发送回主要方法。每个非 main 方法都使用与 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;
}
}
最佳答案
这是因为循环中的行:keyboard.close();
。这将在第一次迭代后关闭Scanner
。之后,您尝试调用 nextInt()
(来自 docs )将抛出:
IllegalStateException
- if this scanner is closed
您应该仅在完全使用完资源后才关闭该资源。
也就是说,不要关闭System.in
。一般规则是,如果您没有打开它,则不应关闭它。
关于java - 当我第二次按下键盘输入时,我的 Do-While 循环中断,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52690929/
我是一名优秀的程序员,十分优秀!