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

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

    But Zechariax wanted an answer with out using try catch

    You can achieve this using NumberForamtter and ParsePosition. Check out this solution

    import java.text.NumberFormat;
    import java.text.ParsePosition;
    
    
        public class TypeChecker {
            public static void main(String[] args) {
            String temp = "a"; // "1"
            NumberFormat numberFormatter = NumberFormat.getInstance();
            ParsePosition parsePosition = new ParsePosition(0);
            numberFormatter.parse(temp, parsePosition);
            if(temp.length() == parsePosition.getIndex()) {
                System.out.println("It is a number");
            } else {
                System.out.println("It is a not number");
            }
        }
    }
    
    0 讨论(0)
  • 2020-12-18 15:36

    Use instanceof to check type and typecast according to your type:

     public class A {
    
        public static void main(String[]s){
    
            show(5);
            show("hello");
        }
        public static void show(Object obj){
            if(obj instanceof Integer){
                System.out.println((Integer)obj);
            }else if(obj instanceof String){
                System.out.println((String)obj);
            }
        }
    }
    
    0 讨论(0)
提交回复
热议问题