Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 4 of 4

Thread: Scanner in Java

  1. #1
    New to the CF scene
    Join Date
    Feb 2011
    Posts
    2
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Scanner in Java

    Hi,

    I'm trying to write a small program that needs to get user input.
    The user should input an integer, and if s/he does not, an exception is thrown. Then the program loops to ask the user for input again. So far, so good.

    The problem is that when it comes time for the user to input data for the second time, the program does not wait for new input, but uses the old, bad input. This causes the program to loop infinitely.

    Code:
    public static Scanner scanner = new Scanner(System.in);
    	
        static public int getMove() throws Exception{
        	while(scanner.hasNextInt()){
        	    int move = scanner.nextInt();
        	    return move;
        	}
        	throw new Exception();
        }
    The getMove() method is called whenever the user needs to input data. I have tried this both with and without the while loop and the hasNextInt(), but it doesn't make a difference. The only way I got it to work was to create a new Scanner each time the method is called, but I feel there should be a better way to do this. Any ideas?

  • #2
    Codeasaurus Rex
    Join Date
    Jun 2008
    Location
    Redmond, WA
    Posts
    659
    Thanks
    31
    Thanked 100 Times in 94 Posts
    Welcome to Coding Forums! I would implement it in this fashion, personally:

    PHP Code:
    import java.util.*;

    class 
    Test {

        public static 
    void mainString[] args ){

            
    // Declare our scanner, much like you did.
            
    Scanner input = new ScannerSystem.in );
            
            
    // Invoke an infinite loop, which we terminate only when our input has been accepted.
            
    while( true ){
            
                try {
                    
    System.out.print( "Please enter a number: " );
                    
    // Read in the next input, and attempt to parse to an integer
                    
    int move Integer.parseIntinput.next() );
                    
    // If we got past the above step without throwing an exception, then
                    // the input is a valid integer (No NumberFormatException or InputMismatchException)
                    
    break;
                }catch( 
    Exception e ){
                    
    // Output an error message and, since we didn't invoke break;, the loop will continue
                    
    System.out.println"Oops! You entered invalid input.\n" );
                }
            
            }
            
            
    System.out.println"Input accepted. Epic win!" );

        }
        

    I've commented in areas to help explain.

    Edit:
    I've tested this code and verified it works as described.
    Last edited by ShaneC; 02-09-2011 at 04:27 AM. Reason: Forgot to welcome. How rude!
    Unless otherwise stated, any code posted is most likely untested and may contain syntax errors.
    My posts, comments, code, and suggestions reflect only my personal views.
    Web Portfolio and Code Snippets: http://shanechism.com

  • #3
    New to the CF scene
    Join Date
    Feb 2011
    Posts
    2
    Thanks
    0
    Thanked 0 Times in 0 Posts
    Thanks for the help, Shane. I tried your code, and it worked perfectly.

    I would still like to know why the nextInt() method that I used does not give the same result. I did not show my whole program, but the method that calls getMove() does so within a while loop and a try block, and catches any exceptions thrown by the getMove() method.

    Code:
    private int getColumn() {
    		while(true){
    		    try{
    		    	if(person == 1){
    		    	    System.out.println("Player 1 enter a column:");
    		    	}
    		    	else{
    		    		System.out.println("Player 2 enter a column:");
    		    	}
    		        int column = Parser.getMove();
    		        return column;
    		    }
    		    catch(Exception e){
    		    	System.out.println("Please enter a valid column (1 - 3)");
    		    }
    		}
    	}
    The selected line shows where the getMove() method is being invoked. It works fine the first time, but if the user enters a non-integer, the loop repeats but does not wait for user input when the getMove() method is called. Do you know why this would happen?
    (getMove() is in the Parser class, so the call to it is valid)
    Last edited by luzgins; 02-09-2011 at 04:45 AM. Reason: clarification

  • #4
    Codeasaurus Rex
    Join Date
    Jun 2008
    Location
    Redmond, WA
    Posts
    659
    Thanks
    31
    Thanked 100 Times in 94 Posts
    Without getting into too much detail, because of the way nextInt() operates you would need to clear the input from the scanner in order to proceed.

    This StackOverflow thread might shed some more light. There's more detailed explanations there as to why it occurs: http://stackoverflow.com/questions/1...-in-hasnextint
    Unless otherwise stated, any code posted is most likely untested and may contain syntax errors.
    My posts, comments, code, and suggestions reflect only my personal views.
    Web Portfolio and Code Snippets: http://shanechism.com


  •  

    Posting Permissions

    • You may not post new threads
    • You may not post replies
    • You may not post attachments
    • You may not edit your posts
    •