2016-08-29 61 views
1
... 
    else if(choice == 3) { 

     ArrayList<Integer> shares = new ArrayList<Integer>(); 
     System.out.print("Type in quantity: "); 
     int quantity = Integer.parseInt(reader.nextLine()); 
     System.out.println("Enter total quantity either as a single number or many numbers by pressing enter after each: "); 
     while (reader.hasNextInt()) { 
      int share = reader.nextInt(); 
      shares.add(share); 
     } 
     System.out.println("Enter total price: "); 
     Scanner reader1 = new Scanner(System.in); 
     double price = Double.parseDouble(reader1.nextLine()); 
     int sum = 0; 
     System.out.println((price*quantity)/sum); 
     for(Integer d : shares){ 
      sum += d; 
     return; 
    } 

在這裏,我試圖計算的單個值進行3值(price*quantity)/sum的這是主要的公式,但總和值是通過首先進入一系列的整數然後將其相加,並用於在主計算式。 的問題:計算體積加權價格

  1. 我不能讓While循環時,用戶輸入Null值停下來,我只設法使它停止當用戶輸入一個字母而不是數字

  2. 目前我運行這個程序我得到一個結果Infinity爲什麼?

回答

1
  1. 因爲你正在檢查reader.hasNextInt(),表示將返回唯一的非整數輸入錯誤。

如果你想利用輸入到文件結束,你可以這樣說:

String input = null; 
while(!(input = sc.nextLine()).isEmpty()) { 
    int share = Integer.parseInt(input); 
    shares.add(share); 
} 
  • 你得到Infinity,因爲你是和誰分值爲零。
  • 我想你可能會試圖做到這一點:通過打印出來

    int sum = 0;   
    for(Integer d : shares){ 
        sum += d; 
    } 
    System.out.println((price*quantity)/sum); 
    
    +0

    我想通了,總和爲0,但我不知道它爲什麼是0和我做循環檢查如果輸入的值是一個整數,因爲我無法使其以任何其他方式工作......來吧你的答案根本沒有幫助 – likyy2

    +0

    你正在得到因爲你已經完成了這個'int sum = 0;' – Shahid

    +0

    如何解決它? – likyy2