Scanner sc = new Scanner(System.in);
System.out.println("Enter whatever you want");
String st = sc.nextLine();
try {
String d = String.valueOf(st);
if (d == (String) d) {
System.out.println((String) d);
} else {
System.out.println(d);
}
} catch(Exception e) {
System.out.println("integer");
}
当我尝试执行此操作时,即使对于整数和双精度值,它也会一直打印“if”部分。找出用户是否输入了字符串,整数或双精度值
尝试将其解析到一个号码类型和捕获异常... –
由于'd'已经是'String'了,所以将它转换为'String'是多余的;那么'd == d'显然总是如此;但是检查'd == d'是多余的,因为你在true和false分支中都做同样的事情。而'String.valueOf(st)'也是多余的,因为'st'已经是'String',所以'st.toString()== st''。 –
要知道用户输入了什么,你可以使用'instanceof'或显然使用sc.hasNextDouble()或hasNextInt() – Imran