从标准输入读取数据并找到它的类型?

时间:2018-03-20 11:11:15

标签: java

我正在尝试从控制台读取数据并找出它是什么类型的数据类型,然后打印一些语句,如果它与类型匹配。

我试过这样,但它仅适用于一个用例,有人可以纠正我需要的修改。

代码

 package euler;
 import java.io.*;
 import java.util.*;

public class Read {

 public static void main(String args[] ) throws Exception {

    BufferedReader br = new BufferedReader(new 
    InputStreamReader(System.in));
    Object obj = br.readLine();


    if(obj instanceof Integer)
    {
        System.out.println("This input of type Integer");
    }

    else if(obj instanceof Float)
    {
        System.out.println("This input of type float");
    }

    else if(obj instanceof String)
    {
        System.out.println("This input of type String");
    }

    else
    {
        System.out.println("This is something else");
    }
  }
}

1 个答案:

答案 0 :(得分:2)

BufferedReader#readLine()返回String。您需要进行一些解析以确定该String是否代表有效的IntegerFloat

String input = br.readLine();

try {
    Integer.parseInt(input);
    System.out.println("Integer");
} catch(NumberFormatException nfe) { // not an int
    try {
        Float.parseFloat(input);
        System.out.println("Float");
    } catch(NumberFormatException nfe) { // not a float either
        System.out.println("String");
    }
}
相关问题