Home > Blockchain >  how to loop, to ask user input for this Java program?
how to loop, to ask user input for this Java program?

Time:11-22

at this program once the exception is caught, the program displays the catch message and program terminates successfully by itself (I need to run the program again manually if want to ask the user input). I dont want the program to finish but automatically it should ask the user to enter a valid number and performs the functions from the beginning, how to write for this?

import java.util.InputMismatchException;
import java.util.Scanner;

public class Main {

public static void main(String[] args) {
    Scanner sc = new Scanner(System.in);

        try {

            System.out.println("Enter a Whole Number to divide: ");
            int x = sc.nextInt();

            System.out.println("Enter a Whole number to divide by: ");
            int y = sc.nextInt();

            int z = x / y;

            System.out.println("Result is: "   z);
        }
        catch (Exception e) {
            System.out.println("Input a valid number");
        }

        finally{
            sc.close();
            }
    }
}

Output

Enter a Whole Number to divide: 
5
Enter a Whole number to divide by: 
a
Input a valid number

Process finished with exit code 0

CodePudding user response:

There are some issues with nextInt that you need to be careful about, You can check out this link: Scanner is skipping nextLine() after using next() or nextFoo()?.

For your program, use a while loop, and you need to be aware of Y could be 0, which would cause an ArithmeticException.

        while (true) {
            try {
                System.out.println("Enter a Whole Number to divide: ");
                // use nextLine instead of nextInt
                int x = Integer.parseInt(sc.nextLine());
                System.out.println("Enter a Whole number to divide by: ");
                int y = Integer.parseInt(sc.nextLine());
                if (y == 0) {
                    System.out.println("divisor can not be 0");
                    continue;
                }
                double z = ((double) x) / y
                System.out.println("Result is: "   z);
                break;
            }
            catch (Exception e) {
                System.out.println("Input a valid number");
            }
        }
        sc.close();
  • Related