How can I check if an input is a integer or String, etc.. in JAVA?

后端 未结 8 772
时光取名叫无心
时光取名叫无心 2020-12-18 14:41

I am wondering how I can check if a user\'s input is a certain primitive type (I mean integer, String, etc... I think it\'s called primitive type?). I want a user to input s

8条回答
  •  无人及你
    2020-12-18 15:25

    class Main{
        public static void main(String args[]){
            String str;
            Scanner sc=new Scanner(System.in);
            int n,
            boolean flag=false;
            while(!flag){
                try{
                    str=sc.nextLine();
                    n=Integer.parseInt(str);
                    flag=true;
                }
                catch(NumberFormatException e){
                    System.out.println("enter an no");
                    str=sc.nextLine();
                }
            }
        }
    }
    

提交回复
热议问题