2014-01-11 64 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

不客气,先生:-) –