如何在JAVA中检查输入是整数还是字符串等?

我想知道如何检查用户的输入是否是某种原始类型(我的意思是整数,字符串等…我认为它被称为原始类型?)。 我希望用户输入内容,然后检查它是否是字符串,并相应地执行某个操作。 (JAVA)我见过这样的代码:

if (input == (String)input) { (RANDOM STUFF HERE) } 

或类似的东西

 if input.equals((String) input) 

他们不工作。 我想知道如何只检查字符串? (已编辑)我想知道是否有function可以做到这一点? 谢谢你的回答

编辑:在每个人的帮助下,我创建了我想要的固定代码:

 package files; import java.util.*; public class CheckforSomething { static Scanner inputofUser = new Scanner(System.in); static Object userInput; static Object classofInput; public static void main(String[] args){ try{ System.out.print("Enter an integer, only an integer: "); userInput = inputofUser.nextInt(); classofInput = userInput.getClass(); System.out.println(classofInput); } catch(InputMismatchException e) { System.out.println("Not an integer, crashing down"); } } } 

不用再回答了,谢谢!

使用instanceof根据您的类型检查类型和类型转换:

  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); } } } 

您可以尝试使用Regex:

 String input = "34"; if(input.matches("^\\d+(\\.\\d+)?")) { //okay } else { // not okay ! } 

这里,

^\\d+表示输入以数字0-9开头,

()? 可能/或可能不会发生

\\. 允许输入一个句点

尝试使用Integer而不是int的instanceof函数。每个基元也有一个类

这个可以吗?

 class Test { public static void main(String args[]) { java.util.Scanner in = new java.util.Scanner(System.in); String x = in.nextLine(); System.out.println("\n The type of the variable is : "+x.getClass()); } } 

输出:

 subham@subham-SVE15125CNB:~/Desktop$ javac Test.java subham@subham-SVE15125CNB:~/Desktop$ java Test hello The type of the variable is : java.lang.String 

但Zechariax希望使用try catch来回答问题

您可以使用NumberForamtter和ParsePosition实现此目的。 看看这个解决方案

 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"); } } }