Beginner: exception thrown in catch; implement a loop? - Java

Developing a program that is similar to creating receipts. Scanner data required: name and price. Attempts to use a trial attempt for a situation where the double will not be entered into the price scanner. It was possible to get this to work, but only if the exception was thrown once; and if I give the wrong input again inside the catch block, it will not work. What can I do to make the program handle exceptions inside catch? I am also just a child who is learning with any free resources that I can get, so the error here may just be a fundamental problem / bad coding practice, and I would like them to be noted.

Thank!

Here is the code:

        Scanner scanPrice = new Scanner(System.in);
        System.out.println("Enter the cost: ");
        try {
            priceTag = scanPrice.nextDouble();
        } catch (InputMismatchException e) {
            System.out.println("Only numbers. Enter the cost again.");
            scanPriceException = new Scanner(System.in);
            priceTag = scanPriceException.nextDouble();
        }

        costs[i] = priceTag;
+4
source share
2

, try catch . , . :

    Scanner scanPrice = new Scanner(System.in);
    System.out.println("Enter the cost: ");
    try {
        priceTag = scanPrice.nextDouble();
    } catch (InputMismatchException e) {
        System.out.println("Only numbers. Enter the cost again.");
        scanPriceException = new Scanner(System.in);
        priceTag = scanPriceException.nextDouble();
    } 

To:

    Scanner scanPrice = new Scanner(System.in);
    while (true) {
        System.out.println("Enter the cost: ");
        try {
            priceTag = scanPrice.nextDouble();
            break;
        } catch (InputMismatchException e) {
            System.out.println("Only numbers. Enter the cost again.");
            scanPrice.next();
        }
    }

try break, nextDouble InputMismatchException.

: , , . , scanPrice.next() . . : ,

+3

while (true) , ( ), " . .". , , " InputMismatchException", break try , , while.

+3

Source: https://habr.com/ru/post/1540149/


All Articles