Java Scanner exception handling

前端 未结 4 1790
挽巷
挽巷 2020-12-18 12:20

I would like to receive a Double from the user and handle the exception thrown in case the user didn\'t input a double/int; in that case I\'d like to ask the user to insert

4条回答
  •  长情又很酷
    2020-12-18 13:06

    This method keeps on executing the same input token until it finds a line separator i.e. input.nextLine() or input.next()

    Check out the following code

    private static double inputAmount()
    {
        Scanner input = new Scanner(System.in);
        while (true)
        {
            System.out.println("Insert amount:");
            try
            {
                double amount = input.nextDouble();
                return amount;
            } 
            catch (java.util.InputMismatchException e)
            {
                input.nextLine();
            }
        }
    }
    

提交回复
热议问题