编写一个Java程序,从输入文件中读取任意数量的行。 输入文件包含一列用于玩家姓名,旁边是每个玩家得分的列。 找 读取的值的数量 总和 平均分(到小数点后两位) 最大值以及相应的名称。 最小值以及相应的名称。
提示:在读入时处理每个数据项并继续。不要保存程序中的所有数据。
===========
我使用2个arraylist来存储数据,然后按升序对arraylist进行排序,然后选择排序的arraylist中的第一个和最后一个数据。 教授不喜欢我对这个节目的处理方式,因为他不想让我消耗这么多公羊并要求我使用上面提到的提示。
我不确定应该采用什么方法解决问题。任何建议将不胜感激。
这是输入文件的一部分
9290 alebam0
9390 davige0
9490 hassa0
9590 luxtt0
9690 raflra0
9790 smithbl0
9890 hallasm0
9990 afflrj0
90 amosre0
190 cottat0
290 luzijc0
3553 philel01
4553 poulcp02
......(数千行)
还有我的代码
import java.util.*;
import java.io.*;
import java.text.DecimalFormat;
public class GCGC
{
public static void main(String[] args) throws IOException
{
ArrayList<String> names = new ArrayList<String>();
ArrayList<Integer> scores = new ArrayList<Integer>();
int nRead = 0; // hold the number of lines
int ListSize; // hold the size of arraylist
final String INPUT_FILE = "/Users/Ali/Desktop/HW1_InputFile.txt";
final String OUTPUT_FILE = "/Users/Ali/Desktop/HW1_Output.txt";
FileWriter fw = new FileWriter(OUTPUT_FILE,false);
PrintWriter pw = new PrintWriter(fw);
File f = new File(INPUT_FILE);
Scanner input = new Scanner(f);
// read all data from input line by line
while (input.hasNext() ) {
scores.add(input.nextInt());
names.add(input.nextLine().trim());
nRead++;
}
ListSize = scores.size(); // size of the arraylist would be used throw the program
int scoresArray[] = new int [ListSize];
String namesArray [] = new String [ListSize];
// This for loop will convert the arraylist into an array
for (int i =0; i<ListSize;i++)
{
scoresArray[i]=scores.get(i);
namesArray[i]=names.get(i);
}
int theSum = sum (scoresArray);
double theAvg = average(scoresArray);
outputData(theSum, theAvg, nRead, pw);
max_and_min(scoresArray, namesArray, pw);
input.close();
pw.close();
System.exit(0);
} // end of main
// #############################################################################
// #################### METHODS ###############################
// #############################################################################
// This method will find and return the average to the main method
public static int sum (int [] scoresArray)
{
int sum=0;
for (int i =0; i < scoresArray.length; i++){
sum+=scoresArray[i];}
return sum;
}
// #############################################################################
// This method will find and return the average to the main method
public static double average (int [] scoresArray)
{
int sum=0;
double avg;
for (int i =0; i < scoresArray.length; i++)
{
sum+=scoresArray[i];
}
avg = (double)sum/scoresArray.length ;
return avg;
}
// #############################################################################
// This method will sort the scores array in an assending order, thus the
// first element of the array will represnet the minimum and the last element of
// the array will represent the maximum.
public static void max_and_min(int [] score, String [] name, PrintWriter pw)
{
int tempNum; String tempName;
boolean fixed = false; // fixed is true once the array is sorted
while (fixed ==false)
{ fixed = true; // ture to exit the while loop once the array is fixed
for (int i =0 ; i<score.length-1 ; i++)
{
if (score[i] > score[i+1])
{
tempNum = score [i+1]; score [i+1] = score[i]; score[i] = tempNum;
tempName = name [i+1]; name [i+1] = name[i]; name[i] = tempName;
fixed = false; // Once we are inside the if statment, that
//means the array is still not fixed
}
}
}
pw.println("The maximum score is: "+score[score.length-1]+" belongs to: "
+name[score.length-1]+"\n\n");
pw.println("The Minimum score is: " + score[0] + " belongs to: "+name[0] +"\n\n");
}
// #############################################################################
// This method is for outputting the report to a text file
public static void outputData(int theSum, double theAvg, int nRead, PrintWriter pw)
{
// DecimalFormat is to format the average
DecimalFormat f = new DecimalFormat("#0.##");
pw.println("\t\t GCGC Statistical Report");
pw.println("###################################################################");
pw.println("\n\n");
pw.println("The number of read values is: " + nRead + "\n\n");
pw.println("The total Sum is: " + theSum + "\n\n");
pw.println("The average Score is: " + f.format(theAvg) + "\n\n");
}
}
答案 0 :(得分:3)
听起来他不想让你在阵列中记住内存中的所有东西。 对于最小值/最大值,您可以检查每行的值是低于还是高于当前值,如果是,则相应地更新新的最小值/最大值。 同样跟踪总和和计数,并从中推导出统计平均值。
似乎整点都不是使用数组,至少这是我解释它的方式
答案 1 :(得分:2)
基本上你的教授要求的是,你要单独阅读每一行并处理它,增加行数,将分数加到运行总数中,并评估分数是高于还是低于你的任何其他分数。到目前为止已读过......
例如......
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.text.NumberFormat;
public class ReadScores {
public static void main(String[] args) {
try (BufferedReader br = new BufferedReader(new FileReader(new File("Scores.txt")))) {
int count = 0;
int tally = 0;
int highest = 0;
int lowest = Integer.MAX_VALUE;
String highestPlayerName = null;
String lowestPlayerName = null;
String text = null;
while ((text = br.readLine()) != null) {
count++;
String[] parts = text.split(" ");
int score = Integer.parseInt(parts[0]);
tally += score;
if (score > highest) {
highest = score;
highestPlayerName = parts[1];
} else if (score < lowest) {
lowest = score;
lowestPlayerName = parts[1];
}
}
System.out.println("Number of entries = " + count);
System.out.println("Sum of scores = " + tally);
System.out.println("Average score = " + NumberFormat.getNumberInstance().format(tally / (double)count));
System.out.println("Highest score of " + highest + " by " + highestPlayerName);
System.out.println("Lowest score of " + lowest + " by " + lowestPlayerName);
} catch (IOException exp) {
exp.printStackTrace();
}
}
}
基于此数据......
9290 alebam0
9390 davige0
9490 hassa0
9590 luxtt0
9690 raflra0
9790 smithbl0
9890 hallasm0
9990 afflrj0
90 amosre0
190 cottat0
290 luzijc0
3553 philel01
...输出
Number of entries = 12
Sum of scores = 81243
Average score = 6,770.25
Highest score of 9990 by afflrj0
Lowest score of 90 by amosre0
通过这种方式,您只需在内存中保存当前信息行,以及提供摘要所需的数据
答案 2 :(得分:0)
正如你的老师所说,你不应该使用arraylists,只需要找到每个值的简单变量。根据需要更新变量,直到获得最终结果。
提示:你需要一个计数器来计算总读数行数,一个变量来存储总和,使用前两个得到平均得分,一个变量保持最大值,另一个保留相应的名称,和另一对夫妇保持最小值和相应的名称。
答案 3 :(得分:0)
QUESTION VARIABLES
Find the count of the number of values read int count
the total sum int sum
the average score double avgScore
the maximum value along with the corresponding name int max, String maxName
the minimum value along with the corresponding name int min, String minName
Intermediate variables int currentScore,String currentName
现在解析输入文件,并在每次迭代中(对于每一行),执行以下操作: -
1)count++
2)将当前分数分配给currentScore
,将当前玩家名称分配给currentName
3)sum+=currentScore
4)检查并比较max
和min
与currentScore
的值,并根据需要进行更新,同时使用{{更新maxName
和minName
1}}如果更新了currentName
或max
。
5)最后在迭代结束后,min
通过这种方式,您将获得所有值,而不会将所有不必要的数据存储到您的程序中。如果我错过了什么,请指出我。