2016-08-02 58 views
0
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”部分。找出用户是否输入了字符串,整数或双精度值

+1

尝试将其解析到一个号码类型和捕获异常... –

+3

由于'd'已经是'String'了,所以将它转换为'String'是多余的;那么'd == d'显然总是如此;但是检查'd == d'是多余的,因为你在true和false分支中都做同样的事情。而'String.valueOf(st)'也是多余的,因为'st'已经是'String',所以'st.toString()== st''。 –

+0

要知道用户输入了什么,你可以使用'instanceof'或显然使用sc.hasNextDouble()或hasNextInt() – Imran

回答

1

为了使用您的代码: 尝试首先解析为整数。如果这是成功的意味着你有一个int。如果这不起作用,尝试解析到一个double,如果这个工作,它意味着你有一个double,否则你有一个字符串。

使用Integer.valueOfDouble.valueOf

System.out.println("Enter whatever you want"); 
    String st = sc.nextLine(); 
    try { 
     Integer d = Integer.valueOf(st); 

     System.out.println("Integer: " + d); 
    } catch (NumberFormatException e) { 
     try { 
      Double d = Double.valueOf(st); 
      System.out.println("Double: " + d); 
     }catch (NumberFormatException nf) { 
      System.out.println("String: " + st); 
     } 
    } 

但我不会建立这种方式。更好的选择是使用sc.hasNextIntsc.hasNextDouble

+1

可能是@ Mureinik的回答是比较相关的 – Imran

-1

试试这个:

String d= String.valueOf(st); 
try{ 
//If double or integer comes here 
    double val = Double.parseDouble(d); 
}catch(Exception e){ 
    //If String comes here 
} 
1

任何输入可以作为字符串进行评估,即使是“2.9”。相反,你可以使用ScannerhasXYZ方法:

if (sc.hasNextInt()) { 
    System.out.println("Integer"); 
} else if (sc.hasNextDouble()) { 
    System.out.println("Double"); 
} else { 
    System.out.println("String"); 
} 
0

您可以使用该程序的输出类型:

import java.util.Scanner; 

public class MyTest { 
public static void main(String args[]) throws Exception { 
    Scanner sc = new Scanner(System.in); 

    System.out.println("Enter whatever you want"); 

    String st = sc.nextLine(); 
    try { 
     Integer.parseInt(st); 
     System.out.println("Integer"); 
    } catch (NumberFormatException nfe) { 

     try { 
      Double.parseDouble(st); 
      System.out.println("Double"); 
     } catch (NumberFormatException nfe2) { 
      System.out.println("String"); 
     } 

    } 
    sc.close(); 
} 
} 
相关问题