Muty
Muty

Reputation: 17

Java reading from Text file

I'm trying to read from text file and printout only unrepeated lines using list.

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

Upvotes: 0

Views: 73

Answers (2)

f1sh
f1sh

Reputation: 11934

You are trying to deal with the same line, but you deal with different ones:

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

Change it do this:

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

Upvotes: 1

Andy Turner
Andy Turner

Reputation: 140299

Instead of calling scan.nextLine() twice, you should store the value in a variable:

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

  // ...
}

Otherwise, you get a different value each time you call scan.nextLine(), so the value you check with contains is different to the one you add.

However, it's simply easier to use a Set<String>, which guarantees not to allow duplicates:

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

Upvotes: 3

Related Questions