【问题标题】:Java: Token rearrangement and character removal with text fileJava:使用文本文件进行令牌重新排列和字符删除
【发布时间】:2016-12-07 22:34:51
【问题描述】:

我正在尝试获取一个文本文件,该文件包含有年龄和姓氏的人名列表,并重新排列它,以便控制台输出从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

【问题讨论】:

  • 使用 input.nextLine().replace(",", "")
  • 你真的应该把整行分割成空白,然后根据需要取每一段

标签: java regex loops java.util.scanner


【解决方案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);

}

【讨论】:

    【解决方案2】:

    您可以通过使用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]);
    }
    

    【讨论】:

    • 我注意到但我不明白的一件事是,你怎么能得到中间的首字母及其周期移动?
    • line.replace(".", "") 会如上所示完成
    猜你喜欢
    • 2021-10-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-04-30
    • 2016-06-14
    • 2019-05-03
    • 1970-01-01
    相关资源
    最近更新 更多