我想利用我目前的计划,在main方法的方法了侧分离averging功能。 我想用扫描仪抓起号码存储到一个数组列表,然后用我的平均数方法,以便抓住那些数量和平均数字加在一起。 然后输出平均代替当前的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));
}
}
//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
}
}
这应该帮助。 祝您好运:)
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() { ... }
}
思考了,我留给你的落实。
下面是一些示例代码
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);
}