【发布时间】:2020-11-27 06:47:24
【问题描述】:
我正在尝试创建一个模拟驾驶汽车的程序。在我的程序中,我有以下循环允许用户“驾驶”他们想要的任何里程:
public void run() {
do {
System.out.println("How many miles would you like to drive?");
int userInput = scanner.nextInt();
if (userInput > 360) {
System.out.println("You don't have enough fuel to drive that far! Please try again.");
run();
}
System.out.println("You are driving: " + userInput + " miles.");
try {
for(int c = 0; c < parts.size(); c++){
parts.get(c).function(userInput);
}
} catch (BreakdownException e) {
}
} while (getBoolean("Keep driving?"));
我想获取 userInput 变量并保存它,以便我可以跟踪油箱中有多少英里。这是我目前拥有的代码:
public void function(int milesDriven) throws BreakdownException {
int mpg = 30;
int gallons = 12;
int totalMiles = gallons * mpg;
int milesLeft = totalMiles - milesDriven;
if(milesLeft <= 0) {
throw new BreakdownException("You ran out of fuel!");
} else if (milesLeft <= (totalMiles / 4)) {
if (getBoolean("You are low on fuel! Refuel?")) {
milesLeft = gallons * mpg;
System.out.println("You now have enough fuel to travel " + totalMiles + " miles.");
}
} else {
System.out.println("You now have enough fuel to travel " + milesLeft + " miles.");
}
}
目前,每次第一个代码块中的循环运行时,第二个代码块中milesDriven 的值都会重置。因此,每次用户“开车”时,他们的油箱都会自动加油。有没有办法可以存储 userInput 值以便它在循环之间保留?
谢谢!
【问题讨论】:
-
您不想在每次调用
function时重置的任何变量的声明都需要移出function到周围的类中,在那里它们可以被任何方法访问班级。您应该研究的相关主题是“变量范围”。