我想采用我当前的程序并将averging函数分离到main方法的方法外。我想将扫描仪抓取的数字存储到数组列表中,然后使用我的平均方法获取这些数字并将数字平均在一起。然后输出平均值代替当前System.out.println,你的平均值是..
请帮我说明一下。我很难理解这一切是如何结合在一起的。
import java.util.Scanner;
class programTwo {
public static void main (String[] args) {
Scanner scan = new Scanner(System.in);
double sum = 0;
int count = 0;
System.out.println ("Enter your numbers to be averaged:");
String inputs = scan.nextLine();
while (!inputs.contains("q")) {
Scanner scan2 = new Scanner(inputs); // create a new scanner out of our single line of input
{
sum += scan2.nextDouble();
count += 1;
System.out.println("Please enter another number or press Q for your average");
}
if(count == 21)
{
System.out.println("You entered too many numbers! Fail.");
return;
}
inputs = scan.nextLine();
}
System.out.println("Your average is: " + (sum/count));
}
}
答案 0 :(得分:1)
Average avg = new Average();
... avg.add(scan2.nextDouble());
System.out.println("Your average is: " + Average.result());
public class Average {
void add(double x) { ... }
double result() { ... }
}
考虑我留给你的实施。
答案 1 :(得分:1)
//added an import here
import java.util.ArrayList;
import java.util.Scanner;
class programTwo
{
//main difference is the average calculation is done within a method instead of main
public static void main( String[] args )
{
Scanner scan = new Scanner(System.in);
ArrayList<Double> myArr = new ArrayList<Double>();
double sum = 0;
int count = 0;
System.out.println("Enter a number to be averaged:");
String inputs = scan.nextLine();
while (!inputs.contains("q")) //input until user no longer wants to give input
{
if (count == 21)
{
break; //this command here jumps out of the input loop if there are 21
}
Scanner scan2 = new Scanner(inputs); // create a new scanner out of our single line of input
myArr.add(scan2.nextDouble()); //simply adding to the array list
count += 1;
System.out.println("Please enter another number or press Q for your average");
inputs = scan.nextLine();
}
Double average = calculate_average(myArr); //go to method calculate average, expect a double to be returned
System.out.println("Your average is: " + average);
}
private static Double calculate_average( ArrayList<Double> myArr ) //method definition
{
Double Sum = 0.0;
for (Double number: myArr) //for loop that iterates through an array list
{
Sum += number; //add all the numbers together into a sum
}
return Sum / myArr.size(); //return the sum divided by the number of numbers in the array list
}
}
这应该有所帮助。祝你好运:))
答案 2 :(得分:0)
以下是一些示例代码
private static void hoot(List<Double> kapow)
{
... do all the stuffs
}
public static void main(final String[] arguments)
{
List<Double> blam = new ArrayList<Double>();
blam.add(1.1);
blam.add(1.2);
blam.add(1.3);
hoot(blam);
}