简体   繁体   English

Java程序接受用户输入的问题

[英]Problem with java program taking user inputs

I'm writing a java program to take a bunch of doubles the user inputs into the command line, add them together, and average them. 我正在编写一个Java程序,将用户输入的内容加倍到命令行,将它们加在一起,然后取平均值。 The user can enter any amount of numbers. 用户可以输入任意数量的数字。 When they enter a negative number, the program does the adding/averaging. 当他们输入一个负数时,程序将进行加/平均。 When i enter a number into cmd line it only lets me enter one. 当我在cmd行中输入数字时,只能输入一个。 Can anyone help me improve this? 谁能帮我改善这个状况?

  import java.util.Scanner;
  public class Average
  {
     public static void main (String[] args)
     {
          Scanner keyboard = new Scanner(System.in);

          System.out.println("Statistics Program, assignment one, program 
          Two. Sean Kerr");
          System.out.println("\nPlease enter a series of numbers. To stop, 
          enter a negative number.");

          //initialize two doubles and an int for our variables: the total numbers,
          //the total added together, and the doubles the user enters into cmd line.

          int amount = 0;
          double totaladded = 0;
          double userinput = 0;

          userinput = keyboard.nextDouble();
          while (userinput >= 0);
          {
             if(userinput > 0 )
             {
                 totaladded = totaladded+userinput;
                 amount++;
             }
          }
          System.out.println("Numbers entered: " + amount);
          System.out.println("The average is: " + totaladded/amount);
      }
 }

use a do while loop instead, 而是使用do while循环,

public static void main (String[] args) {
    Scanner keyboard = new Scanner(System.in);
    int amount = 0;
    double totaladded = 0;
    double userinput = 0;

    do {
        System.out.println("Statistics Program, assignment one, program Two. Sean Kerr");
        System.out.println("\nPlease enter a series of numbers. To stop, enter a negative number.");

        //initialize two doubles and an int for our variables: the total numbers,
        //the total added together, and the doubles the user enters into cmd line.

        userinput = keyboard.nextDouble();

        if(userinput > 0 ) {
            totaladded += userinput;
            amount++;
        }
    } while (userinput >= 0);

    System.out.println("Numbers entered: " + amount);
    System.out.println("The average is: " + totaladded/amount);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM