In: Computer Science
Q. In java, I would like to know, especially how the program detect there is an error which is user should put only numerical data but if user put letter data (five, sixty instead of 5,60), *I want the program display "Invalid data. Please try again" instead of long error message(from the IDE)* when user put letter data(five, sixty stuff...) and GO BACK TO THE BEGINNING SO USER CAN PUT THE DATA AGAIN!
Write a program that counts change. The program should ask for the number of quarters, the number of dimes, the number of nickels and the number of pennies. The program should then compute the value of all the coins and tell the user how much money there is, expressed in dollars. Display a title at the top of the screen when the program first runs. You must use constants for the value of each coin type. Multiply the number of each coin times the value for each coin (the defined constant). Refer to the PowerPoint or video on the use of the constants.
1) if quarters =100 dimes = 100 nickels = 100 pennies = 99
=>expected result = 40.99
2) if quarters = hundred dimes = hundred nickels = nine pennies = hundred
=> expected result ""Invalid data. Please try again" (GO BACK TO THE BEGINNING, SO USER CAN PUT THE DATA AGAIN!) <- this is the part i am struggling. Please Help!
import java.util.Scanner;
public class CountChange {
public static void main(String[] args) {
Scanner sc = new
Scanner(System.in);
double total = 0;
int q, d, n, p;
// loop to ask the user to re-enter
the value
while (true) {
sc = new
Scanner(System.in);
try {
//reading data
System.out.println("Enter quarters: ");
q = sc.nextInt();
System.out.println("Enter dimes: ");
d = sc.nextInt();
System.out.println("Enter nickels: ");
n = sc.nextInt();
System.out.println("Enter pennies: ");
p = sc.nextInt();
// if all are valid breaking the loop
break;
} catch
(Exception e) {
System.out.println("Invalid data. Please try
again");
}
}
//finding total cents
total =
(q*25)+(d*10)+(n*5)+p;
//converting into dollors
total=total/100;
System.out.println("Total :
$"+total);
}
}
Note : Please comment below if you have concerns. I am here to help you
If you like my answer please rate and help me it is very Imp for me