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

后端 未结 8 754
时光取名叫无心
时光取名叫无心 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:19

    Scanner input = new Scanner (System.in);
    
    if (input.hasNextInt()) System.out.println("This input is of type Integer.");
    else if (input.hasNextFloat()) System.out.println("This input is of type Float.");
    else if (input.hasNextLine()) System.out.println("This input is of type string."); 
    else if (input.hasNextDouble()) System.out.println("This input is of type Double."); 
    else if (input.hasNextBoolean()) System.out.println("This input is of type Boolean.");  
    
      else if (input.hasNextLong())
        System.out.println("This input is of type Long."); 
    

提交回复
热议问题