Java:使用文本文件进行令牌重新排列和字符删除

时间:2016-12-07 22:34:52

标签: java regex loops java.util.scanner

我正在尝试使用一个文本文件,其中列出了人口姓氏和姓氏的年龄并重新排列,以便控制台输出从46 Richman, Mary A.转到Mary A. Richman 46。然而,在我试图这样做时,我遇到了问题(如下所示),我不明白为什么它们会发生(之前情况更糟)。

我非常感谢你的帮助!

文字档案:

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.*;
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()) { // Input == people.txt
            String line = input.next().replace(",", "");
            String firstName = input.next();
            String lastName = input.next();
            int age = input.nextInt();

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

        }
    }
}

错误的控制台输出:(如何引发未知的源错误?)

Fresco,Al67
Exception in thread "main" java.util.InputMismatchException
    at java.util.Scanner.throwFor(Unknown Source)
    at java.util.Scanner.next(Unknown Source)
    at java.util.Scanner.nextInt(Unknown Source)
    at java.util.Scanner.nextInt(Unknown Source)
    at Ex2.main(Ex2.java:11)

目标控制台输出:

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

2 个答案:

答案 0 :(得分:1)

您可以通过使用input.nextLine()实际阅读来避免此问题并简化逻辑,如以下代码所示,并带有注释:

while (input.hasNextLine()) {
      String line = input.nextLine();//read next line

      line = line.replace(",", "");//replace , 
      line = line.replace(".", "");//replace .

      String[] data = line.split(" ");//split with space and collect to array

      //now, write the output derived from the split array
      System.out.println(data[2] + " " + data[1] + " " + data[0]);
}

答案 1 :(得分:1)

这将确保名字包含中间的首字母

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

}