2017-06-14 95 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(); 
}