0
Hello I am new in Java language, I would like to know how I could implement a repetition loop every time an Inputmismatchexception type exception was capture, in this case return to the beginning of the program for the user to enter new valid data.
Example of a possible error:
Enter Account data
Number: "abcde"
Unexpected error
So in this case I would like the program to return to the beginning for the user to enter with valid data.
Follow the source code:
public class Program {
public static void main(String[] args) {
Locale.setDefault(Locale.US);
try (Scanner sc = new Scanner(System.in)) {
System.out.println("Enter account data");
System.out.print("Number: ");
int number = sc.nextInt();
System.out.print("Holder: ");
sc.nextLine();
String holder = sc.nextLine();
System.out.print("Initial balance: ");
double initialBalance = sc.nextDouble();
System.out.print("Withdraw limite: ");
double withdrawLimite = sc.nextDouble();
Account account = new Account(number, holder, initialBalance, withdrawLimite);
System.out.println();
System.out.print("Do you like to deposit a amount? (y/n) ");
char r = sc.next().charAt(0);
if (r == 'y') {
System.out.print("Enter amount for deposit: ");
double amountDeposit = sc.nextDouble();
account.deposit(amountDeposit);
System.out.print("New balance: $ " + String.format("%.2f", account.getBalance()));
System.out.println();
}
System.out.println();
System.out.print("Enter amount for withdraw: ");
double amountWithdraw = sc.nextDouble();
account.withdraw(amountWithdraw);
System.out.println("New balance: $ " + String.format("%.2f", account.getBalance()));
System.out.println();
System.out.println("Account Data:");
System.out.println(account);
}
catch (WithdrawException e) {
System.out.println("Withdraw error: " + e.getMessage());
}
catch (InputMismatchException e) {
System.out.println("unexpected error");
}
}
}
The program dealt with a simple example of data entry of a supposed bank account (number, username, initial balance, withdrawal limit), later is asked if the user would like to deposit an amount, and then is made the realization of a withdrawal.