简体   繁体   中英

How to do scanner exception in Java?

I would like to scan a float and an integer. I want to add an exception, if the scanned number is not a float or int, scan again while the input number is not correct. I tried with hasNextFloat and hasNextInt but I didn't really got it right.

package has_exception;

import java.util.Scanner;

public class Has_Exception {

    public static void main(String[] args) {

        Scanner scn = new Scanner(System.in);

        System.out.println("Enter a float!");
        float fl = scn.nextFloat();

        System.out.println("Enter an integer");
        int a = scn.nextInt();

    }
}

try with a parse of string into a float and do this until the user gives a valid input... the initial values of the float will depend of your application, and you can repeat this approach for the integer value

    Scanner scn = new Scanner(System.in);
    float fl = -1.0f;

    while (fl < 0) {
        System.out.println("Enter a float!");

        String x = scn.nextLine();
        try {
            fl = Float.parseFloat(x);
        } catch (NumberFormatException e) {
            System.out.println("Not a float");
        }
    }

You can use do{..}while() with nextLine() instead, for example :

Scanner scn = new Scanner(System.in);
boolean correct = true;
do {
    try {

        System.out.println("Enter a float!");
        float fl = Float.parseFloat(scn.nextLine());
        System.out.println("Enter an integer");
        int a = Integer.parseInt(scn.nextLine());

    } catch (NumberFormatException e) {
        correct = false;
    }
} while (!correct);

scn.close();//close your scanner

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM