【问题标题】:Java: Finding average and numbering linesJava:查找平均线和编号线
【发布时间】:2017-04-23 04:01:10
【问题描述】:

我一直在尝试找出如何在这组数据中找到所有年龄的平均值,并对每一行进行编号。到目前为止,我所做的只是让人无法理解。我的错误通常与转换有关,我不知道如何解决这个问题。

非常感谢您的帮助!

文本文件内容:

75 Fresco, Al
67 Dwyer, Barb
55 Turner, Paige
108 Peace, Warren
46 Richman, Mary A.
37 Ware, Crystal
83 Carr, Dusty
15 Sledd, Bob
64 Sutton, Oliver
70 Mellow, Marsha
29 Case, Justin
35 Time, Justin
8 Shorts, Jim
20 Morris, Hugh
25 Vader, Ella
76 Bird, Earl E.

我工作的代码是:

import java.io.*;

public class Ex2 {
    public static void main(String[] args) throws FileNotFoundException {
        Scanner input = new Scanner(new File("people.txt"));
        while (input.hasNext()) 
        {
            String[] line = input.nextLine().replace(",", "").split("\\s+");
            String age = line[0];
            String lastName = line[1];
            String firstName = "";
            //take the rest of the input and add it to the last name
            for(int i = 2; 2 < line.length && i < line.length; i++)
                firstName += line[i] + " ";

            System.out.println(firstName + lastName + " " + age);
        }
    }
}

我使用失败的代码:

import java.io.*;
import java.util.*;

public class Ex2 {
    public static void main(String[] args) throws FileNotFoundException {
        Scanner input = new Scanner(new File("people.txt"));
        while (input.hasNext()) 
        {
            String[] line = input.nextLine().replace(",", "").split("\\s+");
            String age = line[0];
            String lastName = line[1];
            String firstName = "";
            //take the rest of the input and add it to the last name
            for(int i = 2; 2 < line.length && i < line.length; i++)
                firstName += line[i] + " ";

            for (int count = 1; line.length; count++)
                System.out.println((count+1)+ " " + line[count] + firstName + lastName + " " + age);

            int sum = 0;
            for (int j = 0; j < line.length; j++)
                sum = sum + line[j]
                        double average = sum / line.length;
            System.out.println();
            System.out.println("The average age is: " + average);
        }
    }
}

输出为:

Al Fresco 75
Barb Dwyer 67
Paige Turner 55
Warren Peace 108
Mary A. Richman 46
Crystal Ware 37
Dusty Carr 83
Bob Sledd 15
Oliver Sutton 64
Marsha Mellow 70
Justin Case 29
Justin Time 35
Jim Shorts 8
Hugh Morris 20
Ella Vader 25
Earl E. Bird 76

目标输出为:

1. Al Fresco 75
2. Barb Dwyer 67
3. Paige Turner 55
4. Warren Peace 108
5. Mary A. Richman 46
...

The average age is: NUMBER

【问题讨论】:

  • 能否提供文本文件内容
  • 我的错误,添加它。
  • 检查每一行代码,并为自己描述你认为它做了什么。也去看看 de cmets。看看代码是否真的像你认为的那样做。还要考虑您认为它所做的是否甚至是必要的。停止巧合的编程,从计划开始。
  • 您需要将结束打印代码移出循环。我也会sum人们的年龄totAge += Integer.valueOf (line[0])
  • Guava 中的大多数 recent release 引入了一个不错的新 Stats 类,用于累积统计信息,例如数据系列的 average

标签: java regex loops java.util.scanner


【解决方案1】:

天哪,有这么多方法可以解决这个问题

首先在 Java 中,我们尝试将事物视为对象,在这种情况下,每一行实际上都是一个对象。为了允许以后扩展和调整代码,请从框架开始

所以我们有一个新的

Public Person(
    private int age;
    private String lastName;
    private Sring firstName;

    Public Person(int age, String lName, String fName){
       this.age = age;
       this.lastName = lname;
       this.firstName = fName;
    }
   //add getters here.
)

所以现在我们有了一个对象 我们可以创建一个函数

Array<Person> people = new ArrayList<>;

..for 循环...

String[] line = input.nextLine().replace(",", "").split("\\s+");
Person p = new Person(Integer.parseint(line[0]],line[1],line[2])
people.add(p);

... 或者,您可以使用地图 ...

Map<Integer,Person> people = new ListMap<>;

... 然后做 people.add(p.getAge(),p) …… 地图可以进行各种排序和过滤,具体取决于您选择使用的地图类型。

最后你可以在你的对象上工作以实现上述目标:

Integer total = 0
int i = 0
foreach(Person p: people){
   Integer total = total + p.getAge();
   i++
   System.out.Println(i + "." + p.getFirst() +" "+ p.getLast()+" "+ p.getAge())
}
Float average = Float.parseInt(total) / i;
System.out.Println("The average age is " + average); 

【讨论】:

  • 上面的代码没有经过测试我不会使用它它被设计为一个例子,如果你从对象而不是脚本行的角度来思考是可以实现的。
【解决方案2】:

您也许可以使用以下代码。我对计算平均值的方式进行了一些修改。不需要在 while 循环内使用额外的 for 循环。您可以计算定义两个临时变量的平均年龄。(counttotalAge)。然后,在循环应用程序可以增加计数以识别人数,并且在同一个循环中,您可以将年龄添加到 totalAge 变量中。 (请注意,年龄应转换为 Double)。然后在完成循环后,您可以通过将 totalAge 除以计数来获得年龄。

我注意到在您的代码中,在 while 循环中添加了平均打印部分。这是不正确的,它应该在while循环之外。否则,您的程序将在每行之后打印平均行。

浏览以下代码,我在其中添加了内联 cmets。

import java.io.*;
import java.util.Scanner;

public class Ex2 {
public static void main(String[] args) throws FileNotFoundException {
    Scanner input = new Scanner(new File("people.txt"));
    // to get number of people
    int count=0;
    //to get total age
    double totalAge=0;
    while (input.hasNext()) 
    {
        String[] line = input.nextLine().replace(",", "").split("\\s+");
        String age = line[0];
        String lastName = line[1];
        String firstName = "";
        //take the rest of the input and add it to the last name
        for(int i = 2; 2 < line.length && i < line.length; i++)
            firstName += line[i] + " ";

        //Convert age string into double and add it to totalAge
        totalAge=totalAge+Double.parseDouble(age);
        System.out.println(++count+" "+firstName + lastName + " " + age);
    }
    double average = totalAge / count;
    System.out.println("The average age is: " + average);
}
}

您可以获得给定输入文件的以下输出。

1 Al Fresco 75
2 Barb Dwyer 67
3 Paige Turner 55
4 Warren Peace 108
5 Mary A. Richman 46
6 Crystal Ware 37
7 Dusty Carr 83
8 Bob Sledd 15
9 Oliver Sutton 64
10 Marsha Mellow 70
11 Justin Case 29
12 Justin Time 35
13 Jim Shorts 8
14 Hugh Morris 20
15 Ella Vader 25
16 Earl E. Bird 76
The average age is: 50.8125

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-12-22
    • 2022-01-26
    • 2017-09-01
    • 1970-01-01
    • 2023-03-09
    • 1970-01-01
    • 2023-03-12
    • 1970-01-01
    相关资源
    最近更新 更多