139k views
1 vote
The following do-while loop is suppose to ask for the price for a gallon of gas. The price must a positive number. The price can be an integer value or a double value. for example the price can be 3 or 3.0 or 3.5.

To create a robust program, we must do the data validation and as long as the user is entering a negative value or a String, the program must keep asking the user to enter a valid input.

in this program you need to use some of the scanner methods listed here, make sure to use the proper ones: hasNextInt(), hasNextDouble(), hasNextLine(), hasNext(), nextInt(), nextDouble(), nextLine()

Must flush the buffer at the proper locations in the code

User Kobowo
by
7.1k points

1 Answer

5 votes

Answer:

import java.util.Scanner;

public class qs {

public static void main(String[] args) {

Scanner input = new Scanner(System.in);

double price;

do {

System.out.print("Enter the price for a gallon of gas: ");

while (!input.hasNextDouble()) {

System.out.println("That's not a number!");

input.next(); // this is important!

}

price = input.nextDouble();

} while (price < 0);

System.out.println("The price is " + price);

}

}

User Declan Greally
by
7.3k points