Search code examples
javawhile-loopbufferedreader

ReadLine - execute twice?


I need to be able to read each line of the file for multiple arguments, hence the for loop. After the first one, it does not seem to be reading them anymore, seems to skip the try statement. Any ideas? I'm sure Its something silly I am missing but have been playing about with it and unfortunately time is not on my side.

for (int j = 0; j < ags.length; j++){

 try{
String nameFromFile = null;
BufferedReader InputReader = new BufferedReader(new InputStreamReader(System.in));
while ((nameFromFile = InputReader.readLine()) != null) {

    // Do stuff

} catch (IOException e) {
     System.out.println(e.getMessage());
    }
}

Solution

  • You appear to have two sources you want to compare System.in and args I suggest you read these individually and then compare them.

    Set<String> fromInt = new HashSet<>();
    try (BufferedReader br = new BufferedReader(new InputStreamReader(System.in))) {
        for(String line; (line = br.readLine()) != null;)
            fromIn.add(normalise(line));
    }
    // compare argsList with fromIn. 
    

    e.g.

    for(String arg: args) {
        if (fromIn.contains(normalise(arg))) {
           // something
        } else {
           // something else
        }
    }