【问题标题】:Program outputting Too many lines? [duplicate]程序输出太多行? [复制]
【发布时间】:2014-01-30 05:14:01
【问题描述】:
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.");
     }
     }
 }

}

(此代码只是程序的一部分。如果有点乱,请见谅[我是初学者]) 这就是问题... 它的输出如下:
这个人叫什么名字?
帕特里克
他/她卖了多少钱?
8000
这个人叫什么名字?
他/她卖了多少钱?

粗体线是问题所在。我想输入不同的姓名和金额,但它同时询问我两次。任何帮助将不胜感激。谢谢。

【问题讨论】:

  • 哦,是的,看看this,特别是这个answer

标签: java output


【解决方案1】:

nextDouble 之后,您必须调用scan.NextLine() 来删除留在输出中的行尾字符。

scan.nextDouble 方法只读取数字,没有其他内容。并且因为用户通过按回车“确认”他的输入,他还将在那里发送一个行尾字符。然后 for 循环会将此行尾字符作为第一个问题的输入。因此 - 在读取双精度后,只需调用一个空的 scan.NextLine() 就可以了:-)。

【讨论】:

  • 另请参阅answer 了解解决方法
  • 非常感谢!它完美地工作。 :D
  • 不客气,先生 :-)
猜你喜欢
  • 2018-07-31
  • 2020-03-06
  • 2013-04-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-11-17
相关资源
最近更新 更多