0

ここで何か助けが得られることを願っています。

これは私のファイルのテキストです:

Name: John
Name: Peter
Name: Sarah
Place: New York
Place: London
Place: Hongkong

たとえば、次の arraylist にテキスト ファイルの名前のみを追加するにはどうすればよいですか? これまでのところ、私は...そして、場所を含むすべてを配列リストに追加しています!

private ArrayList<Name> names = new ArrayList<>();

public void load(String fileName) throws FileNotFoundException {
    String text;
    try {
         BufferedReader input = new BufferedReader(new FileReader(fileName));

        while((text = input.readLine()) != null){
            text = text.replaceAll("Name:", "");
            names.add(new Name(text));
        }
    }
    catch (Exception e) {//Catch exception if any
        System.err.println("Error: " + e.getMessage());
    }
}

最後に、John、Peter、Sarah などの名前のみを Name ArrayLIst に追加する必要があります。

私は何か提案をいただければ幸いです、ありがとう!

4

2 に答える 2

1

delimiter にある各行を分割してみてください:。たとえば、次のようになります。

String[] parts = text.split(":");
String part1 = parts[0]; // Name
String part2 = parts[1]; // John
于 2013-04-17T03:21:06.867 に答える
1

if ステートメントを追加し、正規表現を使用して「Place」を含む文字列を探し、これをノックアウトします。それが最も簡単な方法です。

しかし、ここに別の簡単な解決策があります。if 内で OR 演算子を使用して、注意する単語を追加することもできます。

while((text = input.readLine()) != null){
       //gets rid of places 
if !(a.contains("Place")){
           text = text.replaceAll("Name:", "");
           names.add(new Name(text));
         }
    }
于 2013-04-17T03:25:01.147 に答える