2017-06-14 92 views
-6
public static void main(String[] args) { 
    Scanner scan = new Scanner(System.in); 
    int i=scan.nextInt(); 

    // double d=scan.nextDouble(); 
    // Write your code here. 

    Double d = 0.0; 

    try { 

     d = Double.parseDouble(scan.nextLine()); 

    } catch (NumberFormatException e) { 

     e.printStackTrace(); 

    } 

    String s=scan.nextLine(); 

    System.out.println("String: " + s); 
    System.out.println("Double: " + d); 
    System.out.println("Int: " + i); 
} 
+1

这将是巨大的,如果你[格式化你的代码首先](HTTPS:/ /stackoverflow.com/posts/44539167/edit) –

+0

我是新的。不知道如何格式化代码。亲爱的 – Aditya

+2

并说出发生了什么事情与您预期会发生什么。 –

回答

0

这是因为当您输入一个号码并按Enter键时,scan.nextInt()仅消耗输入的号码,而不是“行尾”。当scan.nextLine()执行时,它会消耗在执行scan.nextInt()时提供的第一个输入中仍在缓冲区中的“行尾”。

取而代之,在scan.nextInt()之后立即使用scan.nextLine()

在当前的情况下,你会得到异常

java.lang.NumberFormatException: empty String 

修改后的代码如下,

public static void main(String args[]) 


    { 
     Scanner scan = new Scanner(System.in); 
     int i = scan.nextInt(); 
     scan.nextLine(); 
     // double d=scan.nextDouble(); 
     // Write your code here. 

     Double d = 0.0; 

     try { 

      d = Double.parseDouble(scan.nextLine()); 

     } catch (NumberFormatException e) { 

      e.printStackTrace(); 

    } 

     String s = scan.nextLine(); 

     System.out.println("String: " + s); 
     System.out.println("Double: " + d); 
     System.out.println("Int: " + i); 
    } 
0

你的代码可以修改为以下(记住,它总是一个好主意,关闭扫描仪):

public static void main(String[] args) { 
    Scanner scan = new Scanner(System.in); 

    String s = scan.nextLine(); 
    int i = scan.nextInt(); 
    double d = scan.nextDouble(); 

    System.out.println("String: " + s); 
    System.out.println("Double: " + d); 
    System.out.println("Int: " + i); 
    scan.close(); 
}