2016-04-14 49 views
0

私はテキストファイルから読み込みしようとしており、リストを使って繰り返しのない行だけを出力しようとしています。テキストファイルからのJavaの読み込み

File file = new File("E:/......Names.txt"); 
List<String> names = new ArrayList<String>(); 

Scanner scan = new Scanner(file); 
int j=1; 

while(scan.hasNextLine() && j!=100){ 
    if(!names.contains(scan.nextLine())) 
    names.add(scan.nextLine()); 

    System.out.println(names); 
    j++; 
} 
scan.close(); 

答えて

3

代わりに二回scan.nextLine()を呼び出す、あなたは変数に値を格納する必要があります

String name = scan.nextLine(); 
if (!names.contains(name)) { 
    names.add(name); 

    // ... 
} 

そうでない場合、あなたは別の値にあなたがscan.nextLine()を呼び出すたびに取得するので、あなたはcontainsに確認した値でありますあなたとは違ってadd

しかし、それは重複を許可しないことを保証され、単にSet<String>を使用する方が簡単です:

Set<String> names = new LinkedHashSet<>(); 
// ... 
while (scan.hasNextLine() && names.size() < 100) { 
    if (names.add(scan.nextLine()) { 
    // Only runs if it wasn't there before. 
    } 
} 
1

あなたが同じ行に対処しようとしているが、あなたは別のものを扱う:

if(!names.contains(scan.nextLine())) //this reads a line 
    names.add(scan.nextLine()); //but this reads another line! 

変更する:

while(scan.hasNextLine() && j!=100){ 
    String nextLine = scan.nextLine(); 
    if(!names.contains(nextLine)){ 
    names.add(nextLine); 
    } 
    //... 
関連する問題