2016-12-07 2 views
0

年齢の人の姓と名のリストを持つテキストファイルを取得し、コンソール出力が46 Richman, Mary A.からMary A. Richman 46になるように再配置しようとしています。しかし私の試みでは、私は問題(以下に示す)に遭遇し、なぜそれらが起こっているのかを正確には理解していません(以前の方がはるかに悪かった)。Java:トークンの再配置とテキストファイルによる文字の削除

本当に助けていただきありがとうございます。

テキストファイル:

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 
01コメントを次のコードに示すよう
+0

input.nextLine()。replace( "、"、 "") –

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

} 
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]); 
} 
+0

私が気付いたことと、中期のイニシャルをその期間に移動させますか? – Aramza

+0

'line.replace("。 "、" ")'これは上のように行います – developer

関連する問題