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

后端 未结 8 756
时光取名叫无心
时光取名叫无心 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");
            }
        }
    }
    

提交回复
热议问题