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

or something like

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

EDIT: 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!

解决方案

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
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值