如何在JAVA中检查输入是整数还是字符串等? [英] How can I check if an input is a integer or String, etc.. in JAVA?
问题描述
我想知道如何检查用户的输入是否是某种原始类型(我的意思是整数,字符串等......我认为它是原始类型?)。我希望用户输入内容,然后检查它是否是字符串,并相应地执行某个操作。 (JAVA)
我见过这样的代码:
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 something, then I check if it's a String or not, and do a certain action accordingly. (JAVA) I have seen some codes like this:
if (input == (String)input) { (RANDOM STUFF HERE) }
或类似的东西
if input.equals((String) input)
他们不工作。我想知道我怎么能只检查一个字符串?(已编辑)
我想知道是否有一个功能可以做到这一点?感谢您的回答
And they don't work. I want to know how I can Check for only a String? (EDITED OUT) I was wondering if there was a function that can do that? Thanks for the answers
编辑:在每个人的帮助下,我创建了我想要的固定代码:
With the help of everyone I have created my fixed code that does what I want it to:
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");
}
}
}
不再需要答案了,谢谢!
No need for answers anymore, thanks!
推荐答案
使用 instanceof 根据您的类型检查类型和类型转换:
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);
}
}
}
这篇关于如何在JAVA中检查输入是整数还是字符串等?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!