Question: Hi, so for my code I have everything working. However, when I ask the user to do a fill up again, and the user answers
Hi, so for my code I have everything working. However, when I ask the user to do a fill up again, and the user answers yes, it does it again but for the total, it adds the total from the first round to the second round. For example, first round user input may be:
100
10
200
10
300
10
400
10
500
10
Total miles is 1500
Would you like to do it again, yes
Second round of input is
100
10
200
10
300
10
400
10
500
10
Total miles is 3000 (when it should be 1500).
How do I fix this?
import java.util.Scanner; public class IC6 { public static void main(String[] args) { Scanner in = new Scanner(System.in); double drivMiles = 0; double useGallons = 0; double avg = 0; double totalMiles = 0; double totalGallons = 0; int fillUp = 0; String answer = ""; do { for (fillUp = 0; fillUp <= 4; fillUp++) { System.out.println("Enter the number of miles driven for " + (fillUp + 1)); drivMiles = in.nextDouble(); System.out.println("Enter the number of gallons for " + (fillUp + 1)); useGallons = in.nextDouble(); totalMiles += drivMiles; totalGallons += useGallons; avg = drivMiles / useGallons; String milesPGalln = "miles per gallon. "; String milUse = " miles and used "; String galAvg = " gallon(s). You averaged "; System.out.printf("You drove %.2f %s %.2f %s %.2f %s ", drivMiles, milUse, useGallons, galAvg, avg, milesPGalln); System.out.println(); } in.nextLine(); String galUsed = " miles and your total gallons used is "; String galWord = " gallons. "; System.out.println(); System.out.printf("Your total miles driven is %.2f %s %.2f %s", totalMiles, galUsed, totalGallons, galWord); System.out.println("Would you like to enter another set of fill up?"); answer = in.nextLine(); if (answer.equals("no") || answer.equals("n") || answer.equals("No")) { System.out.println("Thanks for using this fill-up code. "); } } while (answer.equals("yes") || answer.equals("y") || answer.equals("Yes")); in.close(); } }
Step by Step Solution
There are 3 Steps involved in it
Get step-by-step solutions from verified subject matter experts
