我编写了一种方法来打印无法正常工作的对象类型。想法是读取输入,将它们插入ArrayList,然后打印它们的类型。我想提供如下输入
42
3.1415
Welcome to Hackerrank Java tutorials!
并最终以相反的顺序获取输出,例如
String: Welcome to Hackerrank Java tutorials!
Double: 3.1415
Int: 42
它总是以串口形式出现在int,double和String中。下面用一种解决方案提供该方法。我现在正尝试用BufferedReader解决它。
public static void printMethod ( ){
List<Object> arr = new ArrayList<Object>();
Scanner scan = new Scanner(System.in);
int count = 0;
while (scan.hasNextLine()) {
count++;
String line = scan.nextLine();
if( count == 1 ){
try {
Integer v = Integer.valueOf(line.trim());
arr.add(v);
continue;
}
catch (NumberFormatException nfe) {
}
}
if ( count == 2 ){
try {
Double d = Double.valueOf(line.trim());
arr.add(d);
continue;
}
catch (NumberFormatException nfe) {
}
}
arr.add(line);
}
for (int i = arr.size() - 1; i >= 0; i--) {
Object obj = arr.get(i);
Class<?> type = obj.getClass();
String[] s = type.getName().toString().split("\\.") ;
if ( s[s.length - 1 ].equals("Integer") )
System.out.println( "Int" + ": " +obj.toString());
else
System.out.println(s[s.length - 1 ] + ": " +obj.toString());
// System.out.println( );
}
}
答案 0 :(得分:2)
如果我理解你的问题,那么你需要解析支持的类型。由于您的问题列出了Integer
,Double
和String
,我会向您展示一种解析这些问题的方法。另外,我使用Scanner
。把它们放在一起,它可能看起来像
List<Object> arr = new ArrayList<Object>();
Scanner scan = new Scanner(System.in);
while (scan.hasNextLine()) {
String line = scan.nextLine();
try {
Integer v = Integer.valueOf(line.trim());
arr.add(v);
continue;
} catch (NumberFormatException nfe) {
}
try {
Double d = Double.valueOf(line.trim());
arr.add(d);
continue;
} catch (NumberFormatException nfe) {
}
arr.add(line);
}
for (int i = arr.size() - 1; i >= 0; i--) {
Object obj = arr.get(i);
Class<?> type = obj.getClass();
System.out.printf("%s: %s%n", type.getName(), obj.toString());
}
我跑了(并收到了你预期的输出)lke
42
3.1415
Welcome to Hackerrank Java tutorials!
java.lang.String: Welcome to Hackerrank Java tutorials!
java.lang.Double: 3.1415
java.lang.Integer: 42