Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

141
Visualizações
Storing a value created from user input inside a loop for use in other iterations of the loop

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!

over 4 years ago · Santiago Trujillo
1 Respostas
Responde à pergunta

0

If you don't want to change things up too much, one easy way would be to simply accumulate the user input with another variable, and pass that value into the function method instead of the user input that updates on each loop. So for example, outside of the do-while loop you would have:

int milesDriven = 0;

Then, each time the user gives a new input, add that value to the miles driven:

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

And finally pass that value into the function method instead of the user input:

parts.get(c).function(milesDriven);
over 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda