0
votes

Okay so I'm having a slight problem with scanner advancing an extra line. I have a file that has many lines containing integers each separated by one space. Somewhere in the file there is a line with no integers and just the word "done". When done is found we exit the loop and print out the largest prime integer that is less than each given integer in each line(if integer is already prime do nothing to it). We do this all the way up until the line with "done".

My problem: lets say the file contains 6 lines and on the 6th line is the word done. My output would skip lines 1, 3 and 5. It would only return the correct values for line 2 and 4.

Here's a snippet of code where I read the values in:

Scanner in = new Scanner(
                new InputStreamReader(socket.getInputStream()));
        PrintStream out = new PrintStream(socket.getOutputStream());

        while(in.nextLine() != "done"){


            String[] arr = in.nextLine().split(" "); 

Now I sense the problem is that the nextLine call in my loop advances the line and then the nextline.split call also advances the line. Thus, all odd number lines will be lost. Would there be another way to check for "done" without advancing a line or is there a possible command I could call to somehow reset the scanner back to the start of the loop?

2
Use the .hasNextLine scanner method instead - Jacob B.
Yup that would work however I want this to respond to the word "done" itself. Meaning, I want it to search out for the word instead of just getting to done and realizing there is no line after. Hopefully that makes sense. "done" is a keyword in my program sent by the client to the server to tell the server its done sending messages and that it should shut off. Its silly, I know. - John Lutz
Note that, in general, you should never compare Strings using == or !=. The result is probably not what you expect it to be. Instead String#equals does what people generally intend. Search for it, there are plenty questions with answers that explain this issue. - Zabuzard
thanks for the help! yup that was a bad mistake - John Lutz
Why is this tagged "TCP"? - David Hoelzer

2 Answers

4
votes

The problem is you have 2 calls to nextLine() try something like this

String line = in.nextLine();
while (!"done".equals(line)) {
     String[] arr = line.split(" ");

     // Process the line

     if (!in.hasNextLine()) {
         // Error reached end of file without finding done
     }

     line = in.nextLine();
}

Also note I fixed the check for "done" you should be using equals().

-1
votes

I think you are looking for this

while(in.hasNextLine()){
    String str  = in.nextLine();
    if(str.trim().equals("done"){
        break;
    }else{
        String[] arr = str.split("\\s+");
        //then do whatever you want to do 

    }
}