2014-01-11 60 views
0
import java.util.Scanner; 
public class Sales 
{ 
public static void main (String[] args) 
{ 

Scanner scan = new Scanner(System.in); 

String[] name = new String[5]; 
double[] sales = new double[5]; 

    for (int i=0; i<5; i++) { 
    System.out.println ("What is the name of the person?"); 
    name[i] = scan.nextLine(); 
    System.out.println ("How much did he/she sell?"); 
    sales[i] = scan.nextDouble(); 
    } 
    for (int j=0; j<5; j++) { 
    System.out.println (name[j] + " sold " + sales[j]); 
    } 


    int sum = 0; 
    for (double k : sales){ 
    sum+=k; 
    } 

    double avg = sum/5; 
    System.out.println ("The average sales is: " + avg); 

    for (int i = 0; i < 5; i++) { 
    if (sales[i] >= avg){ 
    System.out.println (name[i] + " sold more than the average sales."); 
    } 
    } 
} 

}程序輸出太多行?

(此代碼僅是程序的一部分..對不起,如果它有點凌亂[IM初學者]) 這是問題... 它輸出這樣的:
什麼是這個人的名字?
Patrick
他/她賣了多少?
這個人的名字是什麼?
他/她賣了多少?

粗體的行是問題。我想輸入不同的名稱和金額,但它同時要求我兩次。任何幫助將不勝感激。謝謝。

+1

哦,是的看看[這個](http://stackoverflow.com/questions/17538182/getting-keyboard-input/17538216#17538216)和特殊的這[回答](http://stackoverflow.com/a/13102066/2415194) – nachokk

+0

當然,有一刻。 – pmcg521

回答

4

nextDouble之後,您必須撥打scan.NextLine()以消除輸出中留下的行尾字符。

scan.nextDouble方法只讀取數字,沒有別的。並且由於用戶通過按回車「確認」了他的輸入,他還會在那裏發送結束字符。 for循環會將這個行尾字符作爲第一個問題的輸入。因此 - 在讀取雙精度數據後,只需調用一個空的scan.NextLine()即可,您將會很好:-)。

+2

另請參閱此[解決方法](http://stackoverflow.com/a/13102066/2415194)解決方法 – nachokk

+0

非常感謝!它完美的作品。 :D – pmcg521

+0

不客氣,先生:-) –