从键盘分别输入通过空格分割的整型(int)、浮点型(double)、字符型(String)、布尔型(boolean),根据读取的内容判断他们的类型并将他们解析为正确的对象,并都放到一个数组中。输出各个对象的类型
输入格式:
字符串
输出格式:
数据类型
输入样例:
在这里给出一组输入。例如:
2.1 true 123 abcde
输出样例:
在这里给出相应的输出。例如:
double boolean int String
代码长度限制
16 KB
时间限制
400 ms
内存限制
64 MB
答案:
import java.util.ArrayList;
import java.util.Collections;
import java.util.Scanner;
//主函数
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
String str = in.nextLine();
String[] split = str.split(" ");
Object[] obj = new Object[split.length];
boolean flag=true;
for(int i=0;i<split.length;i++) {
if(isInt(split[i])) {
obj[i]=Integer.valueOf(split[i]);
}
else if (isDouble(split[i])) {
obj[i]=Double.valueOf(split[i]);
}
else if (isBoolean(split[i])) {
obj[i]=Boolean.valueOf(split[i]);
}
else {
obj[i]=split[i];
}
}
for(Object ob : obj) {
if(flag) {
System.out.print(getTypeName(ob));
flag =false;
}
else {
System.out.print(" "+getTypeName(ob));
}
}
}
static boolean isInt(String str) {
try {
int parseInt = Integer.parseInt(str);
return true;
} catch (NumberFormatException e) {
// TODO Auto-generated catch block
return false;
}
}
static boolean isDouble(String str) {
try {
double parseDouble = Double.parseDouble(str);
return true;
} catch (NumberFormatException e) {
// TODO Auto-generated catch block
return false;
}
}
static boolean isBoolean(String str) {
if(str.equals("true") || str.equals("false")) {
return true;
}
else {
return false;
}
}
public static String getTypeName(Object obj) {
if (obj instanceof Integer) {
return "int";
} else if (obj instanceof Double) {
return "double";
} else if (obj instanceof String) {
return "String";
}else if (obj instanceof Boolean) {
return "boolean";
} else {
return "Unknown";
}
}
}