gpt4 book ai didi

java - 创建数组列表

转载 作者:行者123 更新时间:2023-12-02 06:14:38 26 4
gpt4 key购买 nike

我想采用我当前的程序并将平均函数分离到主方法之外的方法中。我想将扫描仪抓取的数字存储到数组列表中,然后使用我的平均方法抓取这些数字并将这些数字平均在一起。然后输出平均值代替当前的 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
}
}

这应该有帮助。祝你好运:)

关于java - 创建数组列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21608990/

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