I'm trying to create a program that simulates driving a car. In my program, I have the following loop to allow the user to "drive" however many miles they wish:
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?"));
I would like to take the userInput variable and save it so that I can keep track of how many miles are in the gas tank. This is the code I currently have for that:
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.");
}
}
Currently, each time the loop in the first code block runs, the value for milesDriven in the second code block resets. Thus, every time the user "drives", their gas tank automatically refills. Is there a way I can store the userInput value so that it retains between loops?
Thanks!