gpt4 book ai didi

java - 传递一个数组,该数组的值是根据用户输入从多个文件中提取的

转载 作者:行者123 更新时间:2023-12-01 18:39:56 25 4
gpt4 key购买 nike

import java.io.*;
import java.util.Scanner;


public class Kazarian_ArrayProcessing
{


public static void main(String[] args) throws Exception
{
inputData();
mean(data);
// I am trying to pass in an array since the mean method
// accepts an array in the parameters but I'm having trouble doing that
// since the array doesn't have a fixed value but instead pulls from a
// specific file


/*sum(data);
max(data);
min(data);*/

}

// checks if file exists and if it does it pulls in the values from the file and
// puts them into an array called data
public static int[] inputData() throws Exception
{
Scanner keyboard = new Scanner(System.in);
System.out.println("Please enter a file name: ");
String inputFile = keyboard.next();
File file = new File(inputFile);

if (!file.exists())
{
System.out.println("This file does not exist!");
System.exit(0);
}

// do this stuff if file does exist

Scanner readFrom = new Scanner(file);
int numberOfElements = readFrom.nextInt();
int [] data = new int[numberOfElements];

for (int i = 0; i < data.length; i++)
{
if (readFrom.hasNextInt())
{
int start = readFrom.nextInt();
data[i] = start;
//System.out.println(data[i]);
}

}

return data;
}

// calculates the mean by pulling in the values from a text file and adding them to
// total and then taking the average
public static double mean(int[] array) throws Exception
{
double average;
double total = 0;

File file = new File("inputFile1.dat");
Scanner readFrom = new Scanner(file);
readFrom.nextInt();

for (int i = 0; i < array.length; i++)
{
if (readFrom.hasNextInt())
{
int start = readFrom.nextInt();
array[i] = start;
}

}

for (int j = 0; j < array.length; j++)
{
total += array[j];

}

average = total / array.length;
System.out.printf("The mean of all elements is: %.2f" + "\n" , average);
return average;
}

我需要以某种方式将数组传递给 mean 方法才能完成其工作,但我有这样做很困难,因为我的数组内部没有固定数量的元素,而且我不知道如何以这种方式处理它。

最佳答案

int[] data = inputData();
mean(data);

调用mean时从哪里获取数据?

您需要先将数组分配给 data,然后才能将其作为参数发送给m​​ean(int[]array);

调用inputData会返回一个数组,因此将其内容存储到data中,然后使用mean(data)将数据传递给mean();//参见上面的代码

关于java - 传递一个数组,该数组的值是根据用户输入从多个文件中提取的,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20361129/

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