【发布时间】: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