【问题标题】:How can I check if an input is a integer or String, etc.. in JAVA?如何在 JAVA 中检查输入是整数还是字符串等?
【发布时间】:2014-09-13 04:41:38
【问题描述】:

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

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

或类似的东西

if input.equals((String) input)

而且它们不起作用。我想知道如何仅检查字符串?(已编辑) 我想知道是否有一个功能可以做到这一点?感谢您的回答

编辑:在大家的帮助下,我创建了我想要的固定代码:

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

    }

 }



 }

不再需要答案了,谢谢!

【问题讨论】:

  • 什么 input它来自哪里,以及如何? IE。如果它是一个字符串,那么它将永远是一个字符串..并且强制转换没有意义。

标签: java


【解决方案1】:

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

【讨论】:

  • 这适用于这种情况,但不适用于扫描仪。 :(
  • 如果我接受stdio 的输入会怎样?在这种情况下我需要帮助。
【解决方案2】:

你可以用正则表达式试试这个:

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

这里,

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

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

\\. 允许输入一个句点

【讨论】:

    【解决方案3】:
    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."); 
    

    【讨论】:

      【解决方案4】:
      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();
                  }
              }
          }
      }
      

      【讨论】:

        【解决方案5】:

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

        目前正在参加编码训练营,并且必须解决类似的问题。我们引入布尔值并根据 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);
                    }
                }
            }
        }
        

        【讨论】:

          【解决方案6】:

          这样好吗?

          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
          

          【讨论】:

            【解决方案7】:

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

            【讨论】:

            • 这看起来很不错,但我不是那么先进(对不起)并且改变了我对整个 Try catch 的想法,它看起来比这个复杂的代码更容易。不过还是谢谢 :)
            • 我同意撒迦利亚。 Try catch 是一个简单的解决方案。但如果您没有该选项,您可以随时使用它。
            • 好的,还有没有办法使用 if(randomVar = (int)) {} 或类似的东西?那将是最有用的。
            【解决方案8】:

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

            【讨论】:

            • 你能提供更多的描述或代码吗?不知道怎么用,谢谢
            猜你喜欢
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2017-12-04
            • 2013-08-12
            • 2022-01-10
            相关资源
            最近更新 更多