【问题标题】:I couldn't get average, largest and smallest value from text file我无法从文本文件中获取平均值、最大值和最小值
【发布时间】:2020-06-16 09:40:31
【问题描述】:

为什么我不能计算我的 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

【问题讨论】:

  • 您正在计算文件每条记录的平均大小。您应该将内容读取到列表中,然后从整个列表中计算值,而不是在每个 Q2 上

标签: java arrays algorithm file


【解决方案1】:

如果您有一个数组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

【讨论】:

  • 我怀疑 OP 也想知道谁有最低和最高分数。否则,这显然是要走的路。
  • @Magnilex 你好,这是可能的,但在他的最后一个输出中,没有与最小和最大分数相关联的名称,并且在帖子的开头他谈到了所有分数的 avg、min 和 max,没有谈论业主的名字。
  • 嘿,dariosicily,你认为有一种方法可以让我不必手动输入这些整数值吗? :)
  • @applePine 你好,如果你想在没有流的情况下保持简单,你可以创建一个 new int[] scores = new int[list.size()] 并在你的列表上循环放置 score[i] 元素等于你的列表元素 @987654325 @.
【解决方案2】:

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

【讨论】:

  • 如何将所有这些记录和统计数据从文本文件解析到 csv 文件?
  • 假设您正在谈论 score.txt 文件。您可以在Link 参考实施。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-07-01
  • 1970-01-01
  • 2021-11-02
  • 1970-01-01
  • 2023-03-15
  • 2017-10-01
  • 1970-01-01
相关资源
最近更新 更多