Я не мог получить среднее, наибольшее и наименьшее значение из текстового файла - PullRequest
1 голос
/ 16 июня 2020

Почему я не могу вычислить все целочисленные значения в моем файле score.txt, чтобы правильно распечатать средний, наименьший и наибольший результат на консоли?

Задача состоит в том, чтобы сохранить каждую запись (имя и оценка) в массиве и может обрабатывать массив объектов, чтобы определить:

  • среднее значение всех оценок
  • наибольшую оценку и
  • наименьшую оценку

мой файл score.txt:

name:   score:
James   10
Peter   40
Chris   20
Mark    24
Jess    44
Carter  56
John    21
Chia    88
Stewart 94
Stella  77

Мой исходный код:

public class Q2 
{
    private String name = "";
    private int point = 0;

    public static void main(String[] args) 
    {
        Scanner keyboard = new Scanner(System.in);

        //prompt user for input file name 
        System.out.println("Enter file name: ");
        String findFile = keyboard.next();

        //invoke readString static method 
        readFile(findFile);

        //output the file's content
        System.out.println(readFile(findFile));


    }//end of main



    public static String readFile(String file)
    {
        String text = " ";

        try 
        {
            Scanner scanFile = new Scanner(new File (file));
            ArrayList<Q2> list = new ArrayList<Q2>(); 
            String name = "";
            int score = 0;
            int count =0; 


            while(scanFile.hasNext())
            {
                 name = scanFile.next();

                 while(scanFile.hasNextInt())
                 {
                     score = scanFile.nextInt();
                     count++;

                 }

                 Q2 data = new Q2(name, score);
                    list.add(data);


            }
            scanFile.close();

            for(Q2 on : list)
            {
                on.calAverage();
                on.smallAndLarge();
                System.out.println(on.toString());
            }


        } 
        catch (FileNotFoundException e) 
        {
            System.out.println("Error: File not found");
            System.exit(0);
        }
        catch(Exception e)
        {
            System.out.println("Error!");
            System.exit(0);
        }

        return text;

    }//end of readFile 

    /**
     *  Default constructor for
     *  Score class
     */
    public Q2()
    {
        this.name = "";
        this.point = 0;
    }

    public Q2(String name, int point)
    {
        this.name = name;
        this.point = point;
    }


    public String getName() {
        return name;
    }



    public void setName(String name) {
        this.name = name;
    }



    public int getPoint() {
        return point;
    }



    public void setPoint(int point) {
        this.point = point;
    }



    /**
     * This calAverage void method is
     * to compute the average of 
     * total point value
     */
    public void calAverage()
    {
        double average = 0.0;
        int sum = 0;

        //compute the sum of point
            sum += getPoint();


        //compute the average of sum 
        average = sum / 10;
        System.out.println("The Average score is " + average );


    }//end of calAverage method 

    public void smallAndLarge()
    {
        int smallest = 0;
        int largest =0;

        smallest = point;
        for(int index = 2; index < 11; index++)
        {
            if(point > largest)
                largest = point;
            if(point < smallest)
                smallest = point;
        }
        System.out.println("The largest num is :" + largest);
        System.out.println("The Smallest num is : " + smallest);
    }


      public String toString() 
      {
            return String.format("\n%s %d\n", getName(), getPoint());
       }


}

Результат, который я получил при вызове:

Enter file name: 
scores.txt
The Average score is 1.0
The largest num is :10
The Smallest num is : 10

James 10

The Average score is 4.0
The largest num is :40
The Smallest num is : 40

Peter 40

The Average score is 2.0
The largest num is :20
The Smallest num is : 20

...etc...

То, что я хочу, чтобы моя программа выводила на:

The Average score is 47.4
The largest num is : 94
The Smallest num is : 10

Ответы [ 2 ]

1 голос
/ 16 июня 2020

Использование структуры коллекции Java 8:

public static void printResult(List<Q2> list)
{
    IntSummaryStatistics summarizedStats = list.stream().collect(Collectors.summarizingInt(Q2::getPoint));

    System.out.println("The Average score is " + summarizedStats.getAverage());
    System.out.println("The largest num is :" + summarizedStats.getMax());
    System.out.println("The Smallest num is : " + summarizedStats.getMin());
}
1 голос
/ 16 июня 2020

Если у вас есть массив int[] оценок, вы можете использовать класс IntSummaryStatistics и его методы для вычисления среднего, минимального и максимального значений массива, как показано ниже:

int[] scores = { 10, 40, 20, 24, 44, 56, 21, 88, 94, 77 };
IntSummaryStatistics stats = IntStream.of(scores).summaryStatistics();
System.out.println(stats.getAverage()); //<-- 47.4
System.out.println(stats.getMin()); //<-- 10
System.out.println(stats.getMax()); //<-- 94
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...