java—将用户输入创建的值存储在循环中,以便在循环的其他交互中使用

gopyfrb3  于 2021-07-08  发布在  Java
关注(0)|答案(1)|浏览(341)

我正在尝试创建一个模拟驾驶汽车的程序。在我的程序中,我有以下循环,允许用户“驾驶”任意英里:

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值以便它在循环之间保持不变?
谢谢!

bpzcxfmw

bpzcxfmw1#

如果您不想改变太多,一个简单的方法就是用另一个变量来累积用户输入,并将该值传递到 function 方法,而不是在每个循环上更新的用户输入。例如,在do while循环之外,您将有:

int milesDriven = 0;

然后,每次用户提供新输入时,将该值添加到行驶里程:

int userInput = scanner.nextInt();
milesDriven += userInput;

最后将该值传递到 function 方法而不是用户输入:

parts.get(c).function(milesDriven);

相关问题