繁体   English   中英

Java Max和Min值-两种方法

[英]Java Max and Min values- two approaches

我已经完成了这项任务。 但是我的教授不喜欢我的方法。

编写一个从输入文件中读取任意行的Java程序。 输入文件由一列代表球员的姓名,并在其旁边有一列代表每个球员的得分。 查找计数的值的数量,将总和,平均分数(至2个小数位)的最大值与相应的名称一起读取。 最小值以及相应的名称。

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

===========

我使用2个arraylist进行了程序存储数据,然后按升序对arraylist进行排序,然后从排序后的arraylist中选择第一个和最后一个数据。 教授不喜欢我处理程序的方式,因为他不希望我消耗太多的内存并要求我使用上述提示。

我不确定应该采用哪种方法解决问题。 任何建议将不胜感激。 这是输入文件的一部分
9290 alebam0
9390 davige0
9490 hassa0
9590 luxtt0
9690拉夫拉0
9790史密斯
9890 hallasm0
9990 afflrj0
90 amosre0
190 cottat0
第290章
第3553章
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.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

这样,您仅将当前信息行以及为提供摘要所需的数据一起保存在内存中

正如您的老师所说,您不应使用数组列表,而应使用简单变量来查找每个值。 根据需要更新变量,直到获得最终结果。

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

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)检查并比较currentScore中的maxmin值,并根据需要更新它们,如果maxmin被更新,还用currentName更新maxNameminName

5)最后,迭代结束后, avgScore=(double)sum/count;

这样,您将拥有所有值,而无需将所有不必要的数据存储到程序中。 如果我错过了什么,请指点我。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM