2016-03-07 51 views
0

我不斷收到此錯誤消息,我無法弄清楚發生了什麼。我不斷收到錯誤消息「線程中的異常」main「java.util.NoSuchElementException」,然後說我的掃描器有一個未知的源。Java中的未知源代碼Eclipse

任何想法發生了什麼?

package pizza; 

import java.util.Scanner; 

public class Pizza { 

public static void main(String[] args) { 
    Double diameter; 
    Double radius; 
    Double cost; 
    Double area; 
    final Double costPerInch; 

    //Ask and enter diameter 
    System.out.println("What is the diameter?"); 
    Scanner size = new Scanner(System.in); 
    diameter = size.nextDouble(); 
    size.close(); 
    radius = diameter/2; 

    //Ask and enter price 
    System.out.println("What is the price of the pizza?"); 
    Scanner price = new Scanner(System.in); 
    cost = price.nextDouble(); 
    price.close(); 

    //Calculate cost per inch 
    area = radius * Math.PI; 
    costPerInch = cost/area; 

    //Output results 
    System.out.println("The cost per inch of the pizza is" + costPerInch); 
+0

我編譯了這個罰款。當我嘗試輸入內容時會出現錯誤。它不喜歡直接使用的double。除此之外,你應該沒問題。 – durbnpoisn

+0

你爲什麼要關閉並重新創建掃描儀? –

回答

1

當你調用closeScanner,它也試圖關閉輸入,它的讀取。因此,在您的第一臺掃描儀關閉後,System.in也會關閉,您無法從中讀取其他任何內容。

只是重複使用相同的Scanner,而不是創建一個新的。

Scanner scanner = new Scanner(System.in); 
diameter = scanner.nextDouble(); 
radius = diameter/2; 

System.out.println("What is the price of the pizza?"); 
cost = scanner.nextDouble(); 
scanner.close(); 
0

我編譯並運行它。這裏是你的問題:

size.close(); 

一旦關閉,它完全失去了掃描儀。註釋掉該行,並且代碼有效。