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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/25819889/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 01:14:03  来源:igfitidea点击:

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

java

提问by jiggumbob

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:

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

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!

不需要回答了,谢谢!

采纳答案by Rustam

Use instanceofto check type and typecast according to your type:

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

回答by Asaf Nevo

Try instanceof function with Integer instead of int.. each primitive also have a class

尝试使用 Integer 而不是 int 的 instanceof 函数..每个原语也有一个类

回答by subham soni

Is this ok?

这个可以吗?

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

Output:

输出:

subham@subham-SVE15125CNB:~/Desktop$ javac Test.java 
subham@subham-SVE15125CNB:~/Desktop$ java Test
hello

 The type of the variable is : java.lang.String

回答by subham soni

You may try this with Regex:

你可以用 Regex 试试这个:

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

Here,

这里,

^\\d+says that input starts with a digit 0-9,

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

()?may/or may not occur

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

\\.allows one period in input

\\.允许输入一个句号

回答by Govind

But Zechariax wanted an answer with out using try catch

但是 Zechariax 想要一个不使用 try catch 的答案

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

您可以使用 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");
        }
    }
}

回答by G Bulli Swamy Reddy

class Main{
    public static void main(String args[]){
        String str;
        Scanner sc=new Scanner(System.in);
        int n,
        boolean flag=false;
        while(!flag){
            try{
                str=sc.nextLine();
                n=Integer.parseInt(str);
                flag=true;
            }
            catch(NumberFormatException e){
                System.out.println("enter an no");
                str=sc.nextLine();
            }
        }
    }
}

回答by Ajay Gupta

Scanner input = new Scanner (System.in);

if (input.hasNextInt()) System.out.println("This input is of type Integer.");
else if (input.hasNextFloat()) System.out.println("This input is of type Float.");
else if (input.hasNextLine()) System.out.println("This input is of type string."); 
else if (input.hasNextDouble()) System.out.println("This input is of type Double."); 
else if (input.hasNextBoolean()) System.out.println("This input is of type Boolean.");  

  else if (input.hasNextLong())
    System.out.println("This input is of type Long."); 

回答by Petar_D

Hate to bring this up after 6 years but I found another possible solution.

讨厌在 6 年后提出这个问题,但我找到了另一种可能的解决方案。

Currently attending a coding bootcamp and had to solve a similar problem. We introduce booleans and change their values depending on the result of the try/catch blocks. We then check the booleans using simple if statements. You can omit the prints and input your code instead. Here's what it looks like:

目前正在参加编码训练营,不得不解决类似的问题。我们引入布尔值并根据 try/catch 块的结果更改它们的值。然后我们使用简单的 if 语句检查布尔值。您可以省略打印并输入您的代码。这是它的样子:

import java.io.IOException;
import java.util.Scanner;

public class DataTypeFinder {
    public static void main(String[] args) throws IOException {
        Scanner scan = new Scanner(System.in);
        String input = "";

        while (true) { //so we can check multiple inputs (optional)
            input = scan.nextLine();

            if ("END".equals(input)) { //a way to exit the loop
                break;
            }

            boolean isInt = true; //introduce boolean to check if input is of type Integer
            try { // surround with try/catch
                int integer = Integer.parseInt(input); //boolean is still true if it works
            } catch (NumberFormatException e) {
                isInt = false; //changed to false if it doesn't
            }

            boolean isDouble = true; //same story
            try {
                double dbl = Double.parseDouble(input);
            } catch (NumberFormatException e) {
                isDouble = false;
            }

            if (isInt) {
                System.out.printf("%s is integer type%n", input);
            } else if (isDouble) {
                System.out.printf("%s is floating point type%n", input);
            } else if (input.length() == 1) { //this could be useless depending on your case
                System.out.printf("%s is character type%n", input);
            } else if ("true".equals(input.toLowerCase()) || "false".equals(input.toLowerCase())) {
                System.out.printf("%s is boolean type%n", input);
            } else {
                System.out.printf("%s is string type%n", input);
            }
        }
    }
}