Java最大值和最小值-两种方法 我已经完成了这个任务。但是我的教授不喜欢我的方法。

Java最大值和最小值-两种方法 我已经完成了这个任务。但是我的教授不喜欢我的方法。,java,Java,编写一个Java程序,从输入文件中读取任意数量的行。 输入文件包括一列球员姓名,旁边是一列球员得分。 发现 读取的值数的计数 总数 平均分数(小数点后2位) 最大值以及相应的名称。 最小值以及相应的名称 提示:处理读入的每个数据项并继续。不要在程序中保存所有数据 =========== 我使用2 arraylist来存储数据,然后按升序对arraylist进行排序,然后选择排序后的arraylist中的第一个和最后一个数据。 教授不喜欢我处理这个项目的方式,因为他不想让我消耗这么多的内存,让我使

编写一个Java程序,从输入文件中读取任意数量的行。 输入文件包括一列球员姓名,旁边是一列球员得分。 发现 读取的值数的计数 总数 平均分数(小数点后2位) 最大值以及相应的名称。 最小值以及相应的名称

提示:处理读入的每个数据项并继续。不要在程序中保存所有数据

===========

我使用2 arraylist来存储数据,然后按升序对arraylist进行排序,然后选择排序后的arraylist中的第一个和最后一个数据。 教授不喜欢我处理这个项目的方式,因为他不想让我消耗这么多的内存,让我使用上面提到的提示

我不确定我应该用什么方法来解决这个问题。如有任何建议,将不胜感激。 这是输入文件的一部分
9290 alebam0
9390大力士0
9490 HASA0
9590 luxtt0
9690 raflra0
9790 smithbl0
9890 hallasm0
9990 afflrj0
90 amosre0
190棉0
290 LUSIJC0
3553 Phille01
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");

   }
}
import java.util.*;
导入java.io.*;
导入java.text.DecimalFormat;
公共类GCGC
{
公共静态void main(字符串[]args)引发IOException
{
ArrayList name=新的ArrayList();
ArrayList分数=新建ArrayList();
int nRead=0;//保留行数
int ListSize;//保留arraylist的大小
最终字符串INPUT_FILE=“/Users/Ali/Desktop/HW1_InputFile.txt”;
最终字符串OUTPUT_FILE=“/Users/Ali/Desktop/HW1_OUTPUT.txt”;
FileWriter fw=新的FileWriter(输出文件,false);
PrintWriter pw=新的PrintWriter(fw);
文件f=新文件(输入文件);
扫描仪输入=新扫描仪(f);
//逐行读取输入中的所有数据
while(input.hasNext()){
scores.add(input.nextInt());
name.add(input.nextLine().trim());
nRead++;
}
ListSize=scores.size();//程序将使用arraylist的大小
int scoresArray[]=新的int[ListSize];
字符串名称数组[]=新字符串[ListSize];
//此for循环将arraylist转换为数组

对于(inti=0;i,正如您的老师所说,您不应该使用ArrayList,而应该为每个要查找的值使用简单的变量。根据需要更新变量,直到得到最终结果


提示:你需要一个计数器来计算总读行数,一个变量来存储总和,使用前两个变量来获得平均分数,一个变量用来保持最大值,另一个变量用来保持相应的名称,另一个变量用来保持最小值和相应的名称。

正如你的老师所说,你不应该这样做不要使用ArrayList,对于要查找的每个值,只使用简单的变量。根据需要更新变量,直到得到最终结果


提示:您需要一个计数器来计算总读取行数,一个变量来存储总和,使用前两个变量来获得平均分数,一个变量用来保持最大值,另一个变量用来保持相应的名称,另一个变量用来保持最小值和相应的名称。

听起来他不想让您这么做将内存中的所有内容存储在一个数组中。 对于最小值/最大值,您可以检查每一行的值是否低于/高于当前值,如果是,则相应地更新新的最小值/最大值。 同样地,跟踪总和和计数,并从中推断统计平均值


看起来重点不在于使用数组,至少我是这样解释的

听起来他不想让你把所有东西都塞进数组中。 对于最小值/最大值,您可以检查每一行的值是否低于/高于当前值,如果是,则相应地更新新的最小值/最大值。 同样地,跟踪总和和计数,并从中推断统计平均值


看起来重点不在于使用数组,至少我是这样解释的,基本上你的教授要求你阅读每一行并进行处理,增加行数,将分数添加到总分数中,然后评估分数是高于还是低于你迄今为止读到的任何其他分数。。。

例如

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();
        }
    }

}
输出

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

通过这种方式,你只需在内存中保存当前行信息,以及提供摘要所需的数据。基本上,你的教授要求你单独阅读每行信息并进行处理,增加行数,将分数添加到运行总数中,并评估分数是否高于比你读到的任何其他分数都低

例如

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();
        }
    }

}
输出

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
这样,您只需在内存中保存当前行信息以及提供摘要所需的数据

问题变量

查找读取int count的值数的计数

总和int sum

avgScore平均分加倍

最大值以及相应的名称int max、字符串maxName

最小值以及相应的名称int min、字符串minName

中间变量int currentScore,字符串currentName

现在,解析您的输入文件,并在每次迭代(针对每一行)中执行以下操作:-

1)