首页 文章

整数浮点字符串以编程方式区分

提问于
浏览
0

我想区分int / float / string输入,我试图读取输入

Scanner scan = new Scanner(System.in);

这提供了字符串格式的输入,如果我想检查输入是整数/浮点数还是字符串,我该怎么办?我做了这样的事

try{
 float i = Float.parseFloat(scan.nextLine());
 if(i%1==0){
  then it is integer
 }else{
  it is float
 }
}catch (NumberFormatException e)
 something else, may be string
}

但是有没有java提供的方法或方法来以编程方式识别输入是否为string / int / float .

5 回答

  • 0

    而不是读取 String 然后将其解析为 Float 然后检查它是否为整数 .

    您只需使用Scanner类的 hasNext 函数,如下所示为整数 .

    if(sc.hasNextInt()){
        int n = sc.nextInt();
        System.out.println("n... "+n);
    }
    

    如您想要完全匹配,可以尝试以下方法:

    String str = sc.nextLine();
        try{
            int a = Integer.parseInt(str.trim());
            System.out.println("It's Integer");
        }catch(Exception ex)
        {
            try{
                Float f = Float.parseFloat(str.trim());
                System.out.println("It's Float");
            }catch(Exception e){
                System.out.println(str);
            }           
        }
    
  • 0

    据我所知,没有什么能提供直接检查 .

    您可以使用Integer.parseInt并捕获NumberFormatException . 该异常告诉您它不是整数 . 同样,usr Float.parseFloat . 如果两者都抛出异常,则输入为字符串 .

  • 0

    您可以在 Scanner 中使用 hasNextFoo 方法 . 例如,

    if(scan.hasNextInt()){
        System.out.println(scan.nextInt() + " is int");
    }else if(scan.hasNextFloat()){
        System.out.println(scan.nextFloat() + " is float");
    }else{
        System.out.println(scan.next() + " is String");
    }
    
  • 0

    java.util.Scanner 类具有验证用户输入是否为某种类型的方法

    Scanner userInput = new Scanner(System.in);
                boolean hasNextInt = userInput.hasNextInt();
    

    如果用户输入整数,则返回true .

    boolean hasNextDouble = userInput.hasNextDouble();
            System.out.println(hasNextDouble);
    

    如果用户输入double,则返回true . 否则就是假的

  • 1

    Scanner类有couple of methods,您可以使用它来确定下一个元素的类型 .

    hasNextBigDecimal()
    hasNextBigInteger()
    hasNextBoolean()
    hasNextByte()
    hasNextDouble()
    hasNextFloat()
    hasNextInt()
    hasNextLine()
    hasNextLong()
    hasNextShort()
    

    你可以简单地使用它们

    if(sc.hasNextInt()) {
        System.out.println(sc.nextInt() + " is an Integer.");
    }
    else if(sc.hasNextBoolean()) {
        System.out.println(sc.nextBoolean() + " is a Boolean.");
    }
    

相关问题