Best approach for using Scanner Objects in Java?

Posted by devjeetroy on Stack Overflow See other posts from Stack Overflow or by devjeetroy
Published on 2011-11-16T01:46:55Z Indexed on 2011/11/16 1:50 UTC
Read the original article Hit count: 217

Filed under:
|

Although I'm more of a C++/ASM guy, I have to work with java as a part of my undergrad course at college. Our teacher taught us input using Scanner(System.in), and told us that if multiple functions are were taking user input, it would be advisable that a single Scanner object is passed around so as to reduce chances of the input stream getting screwed up. Now using this approach has gotten me into a situation where I'm trying to use a Scanner.nextLine(), and this statement does not wait for user input. It just moves on to the following statement. I figured there may be some residual cr/lf or other characters in the Scanner that might not have been retrieved are causing the problem. Here is the code.

while(lineScanner.hasNext())
            {
                if(isPlaceHolder(temp = lineScanner.next()))
                {
                    temp = temp.replace("<","");
                    temp = temp.replace(">", "");
                    System.out.print("Enter "+aOrA(temp.charAt(0)) +" " +temp + " : ");
                    temp = consoleInput.nextLine();

                }
                outputFileStream.print(temp + " ");
            }

All of the code is inside a function which receives a Scanner object consoleInput. Ok, so what happens when i run it is that when the program enters the if() the first time, It carries out theSystem.out.print, does not wait for user input, and moves on to the second time that it enters the 'if' block. This time, it takes the input and the rest of the program operates normally. What is even more surprising is that when i check the output file created by the program, it is perfect, just as i want to be. Almost as if the first time input using the scanner is correct. I have solved this problem by creating a new system.in Scanner in the function itself, instead of receiving the Scanner object as a parameter.

  • But I am still very curious to know what the hell is happening and why it couldn't be solved using a simple Scanner.reset().
  • Would it be better to just simply create a Scanner Object for each function?

Thanks,

Devjeet

PS. Although I know how to take input using fileinputstreams and the like, we are not supposed to use it with the homework.

© Stack Overflow or respective owner

Related posts about java

Related posts about scanner