gpt4 book ai didi

java - 跳过 while 语句

转载 作者:行者123 更新时间:2023-12-01 12:23:46 28 4
gpt4 key购买 nike

我在使用一个程序时遇到了一些麻烦,我应该允许用户在程序中输入任意数量的数字,直到他们不再想要为止。然后程序应该计算输入数字的平均值和最大值。我哪里做错了?

import java.util.Scanner;
public class DataSet
{
//Instance Variables
private double newValue;
private double sum;
private int count;
Scanner scan = new Scanner(System.in);


//Constructors
public DataSet()
{
double newValue = 0;
double sum = 0;
int count = 0;
}

public void run()
{
}

public double getaddValueToSet()
{
System.out.println("Please enter a number");
newValue = scan.nextDouble();
count += 1;
return newValue;
}

public double getSum()
{
sum += newValue;
return sum;
}

public double getAverage()
{
double average;
average = sum/count;
return average;
}

public double getMaximum()
{
double max=newValue;
if(newValue >= max)
{
max = newValue;
}
return max;
}

public String toString()
{
String str;
str = "Average: " + getAverage() + "\n" +
"Maximum: " + getMaximum();
return str;
}
}


import java.util.Scanner;

public class DataSetRunner
{
public static void main(String [] args)
{
String answer = "yes";
Scanner scan = new Scanner(System.in);


{
System.out.println("Do you want to enter another number?");
answer = scan.next();
}

while(answer.equals("yes"))
{
DataSet d1 = new DataSet();
double sum, number;


d1.run();
number = d1.getaddValueToSet();
sum = d1.getSum();
answer = scan.nextLine();

System.out.println(d1);
}

}

}

最佳答案

DataSet d1 = new DataSet();
do {
System.out.println("Do you want to enter another number?");
answer = scan.next();
if (answer.equalsIgnoreCase("YES")) {
double sum, number;
d1.run();
number = d1.getaddValueToSet();
sum = d1.getSum();
answer = scan.nextLine();
System.out.println(d1);
} else {
break;
}
} while (true);

关于java - 跳过 while 语句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26499320/

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