Endless loop while using “try and catch ” block inside a “while loop”

前端 未结 4 950
眼角桃花
眼角桃花 2020-12-21 21:56

My program has an endless loop, when I use try and catch block in a while loop.

import java.util.*;
class Try
{
    public          


        
4条回答
  •  旧时难觅i
    2020-12-21 22:27

    The problem is that when you call nextInt you will screw the Scanner and so it cannot be used once nextInt caused in exception. That Scanner is not valid anymore. To get around this, you should read the content as string and cast it, when the cast operation fails, you don't have to worry about anything.

    I would do it like this:

    import java.util.*;
    class Try
    {
        public static void main(String args[])
        {
            Scanner sc=new Scanner(System.in);
            while(true)
            {
                try{
                    System.out.println("Enter a no ");
                    int s=Integer.parseInt(sc.next()); // or sc.nextLine() if you wish to get multi digit numbers 
                 }catch(Exception e)
                   {
                     System.out.println("Invalid input try again");
                   }
            }
        }
    }
    

提交回复
热议问题