【问题标题】:Storing a value created from user input inside a loop for use in other iterations of the loop将用户输入创建的值存储在循环内以用于循环的其他迭代
【发布时间】: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 到周围的类中,在那里它们可以被任何方法访问班级。您应该研究的相关主题是“变量范围”。

标签: java loops for-loop


【解决方案1】:

如果您不想改变太多,一种简单的方法是简单地使用另一个变量累积用户输入,然后将该值传递给 function 方法,而不是在每个变量上更新的用户输入环形。因此,例如,在 do-while 循环之外,您将拥有:

int milesDriven = 0;

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

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

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-10-20
    • 1970-01-01
    • 1970-01-01
    • 2015-07-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多