applePine
applePine

Reputation: 19

I couldn't get average, largest and smallest value from text file

Why couldn't I calculate all the integer value in my score.txt file to get the average, smallest and largest result printed on to the console correctly?

Task is to store each record(name and score) in an array and able to process the array of the objects to determine:

my score.txt file :

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

My Source code:

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


}

The output I got when invoked:

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...

What I want my program to output to:

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

Upvotes: 1

Views: 120

Answers (2)

pcsutar
pcsutar

Reputation: 1831

Using Java 8 collection framework:

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

Upvotes: 1

dariosicily
dariosicily

Reputation: 4547

If you have an array int[] scores, you can the IntSummaryStatistics class and its methods to calculate avg, min and max of the array like below:

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

Upvotes: 1

Related Questions