gpt4 book ai didi

java - java程序接受用户输入的问题

转载 作者:行者123 更新时间:2023-12-02 10:19:39 24 4
gpt4 key购买 nike

我正在编写一个java程序,将用户在命令行中输入的一堆 double 据相加,然后求平均值。用户可以输入任意数量的数字。当他们输入负数时,程序会进行相加/平均。当我在命令行中输入一个数字时,它只允许我输入一个。谁能帮我改进这个吗?

  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);
}
}

最佳答案

使用 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);
}

关于java - java程序接受用户输入的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54432047/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com