напишите программу Java, которая читает в любом количестве строк из входного файла. Входной файл состоит из одного столбца для имен игроков, а рядом с ним - столбец для оценки для каждого игрока. Найдите счетчик количества значений, считанных общей суммой средней оценки (до 2 десятичных знаков), максимального значения вместе с соответствующим именем. минимальное значение вместе с соответствующим именем.
hint: обрабатывать каждый элемент данных, когда он считывается и перемещается. Не сохраняйте все данные в вашей программе.
===========
Я сделал программу, используя 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");
}
}
Похоже, он не хотел, чтобы вы забивали все в памяти в массиве. Для min/max вы можете проверить, что в каждой строке значение было ниже/выше текущего значения, и если да, обновите новый min/max соответственно. Аналогично отслеживайте сумму и счетчик и выведите статистическое среднее из них.
Кажется, что все дело в том, что не используются массивы, по крайней мере, так, как я их интерпретировал
В основном, что спрашивает ваш профессор, вам нужно прочитать каждую строку по отдельности и обработать ее, увеличив количество строк, добавив оценку к общей сумме и оценив, превышает ли счет или меньше, чем любые другие оценки, которые вы читали до сих пор...
Например...
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
Таким образом, вы сохраняете только текущую строку информации в памяти вместе с данными, необходимыми для предоставления сводки
Как сказал ваш учитель, вы не должны использовать arraylists, просто простые переменные для каждого из найденных значений. Обновляйте переменные по мере необходимости, пока не получите окончательный результат.
Советы: вам понадобится счетчик для количества всех прочитанных строк, переменной для хранения общей суммы, используйте те два предыдущих, чтобы получить средний балл, переменную, чтобы сохранить максимальное значение, а другое - сохранить соответствующее имя, а другое чтобы сохранить минимальное значение и соответствующее имя.
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
, текущему имени игрока to currentName
3) sum+=currentScore
4) Проверяйте и сравнивайте значения в max
и min
с currentScore
и обновляйте их по мере необходимости, также обновляйте maxName
и minName
с currentName
если currentName
max
или min
.
5) Наконец, после окончания итерации, avgScore=(double)sum/count;
Таким образом, вы будете иметь все значения, не сохраняя все ненужные данные в вашей программе. Пожалуйста, укажите мне, если я что-то пропустил.