Results 1 to 6 of 6

Thread: Odd bug

  1. #1
    Join Date
    Sep 2011
    Posts
    18
    Rep Power
    0

    Default Odd bug

    So I wrote this program, the instructions are in the code, and it has the oddest bug that I can't figure out how to fix! When it runs and compiles, when it gets to the isSingle() and isWord() methods, it just prints out "Please enter a single word" and then skips to the next methods!

    So I wrote the isSingle() method out as a separate program and ran it, and it works fine!?

    Why won't it run correctly in my actual program?

    Thanks!

    Separated out:
    Java Code:
     
    import java.util.Scanner;
    
    public class Single
    {
    	Scanner keyboard = new Scanner(System.in);
    
    	public void isSingle()
    	    {
    	        String single;
    
                System.out.println("Please enter a single word");
                single = keyboard.nextLine();
    
                String[] tokens = single.split("\\s+");
    
                boolean doSingle = true;
                while (doSingle == true)
                {
                    if (tokens.length == 1 )
                    {
                        System.out.println(single);
                        doSingle = false;
                    }
                    else
                    {
                        System.out.println("You must enter only one word.");
                        System.out.println("Please enter one word.");
                        single = keyboard.nextLine();
                        tokens = single.split("\\s+");
                    }
                }
           }
    
           public static void main(String[] args)
           {
    		   Single single = new Single();
    		   single.isSingle();
    	   }
       }
    And here it is in the whole program. Note: isWord() method is/does the same thing as isSingle()
    Java Code:
    import java.util.Scanner;
    
    public class Echo
    {
        /** 
         * Main should:
         *     - Create a Scanner object to get keyboard input
         *     - Create an Echo object and pass the constructor the Scanner
         *     - Call the Echo's "begin" method
         * Needs: 
         *     - A field initialized in the constructor
         *     - A method that: 
         *              - Ask the user for a line of text, echo it back        
         *              - Ask the user for a line of text containing 3 words separated by spaces, echo it back
         *                with each word on its own line
         *              - Ask the user for an integer number, echo it back
         *              - Ask the user for a single word, echo it back
         *              - Ask the user for a real number (with a decimal point), echo it back
         *              - Ask the user for a single word, echo it back
         */
       
        Scanner keyboard = new Scanner(System.in);                              // Create scanner object
    
                public void isPhrase()
                {
                    String phrase;                                               // To hold the user's phrase
                   
                    System.out.println("Hello, my name is Echo.");
                    System.out.println("Please enter a sentence longer than three words"); 
                    phrase = keyboard.nextLine();                                // Saves user input as String phrase
                
                    String[] tokens = phrase.split(" ");
    
                    boolean doPhrase = true;
                    while(doPhrase == true)
                    {
                        if(tokens.length > 3)
                        {
                            for (String p : tokens)
                                System.out.print(p + " ");
                        doPhrase = false;
                        }
                        else
                        {
                            System.out.println("Must be a phrase sentence longer than three words");
                            System.out.println("Please enter a sentence longer than three words");
                            phrase = keyboard.nextLine();
                            tokens = phrase.split(" ");
                        } 
                    } 
                }
                
                public void isThree()
                {
                    String three;
    
                    System.out.println("\nNow enter 3 words separated by spaces");
                    three = keyboard.nextLine();                                // Saves user's input as String phrase 
    
                    String[] tokens = three.split(" ");                        // Split token method prints string one 
               
                    boolean doWhile = true;
                    while (doWhile == true)            
                    {
                        if (tokens.length == 3)
                        {
                        for (String t : tokens)                                     // line at a time 
                            System.out.println(t); 
                        doWhile = false;
                        }
                        else 
                        { 
                            System.out.println("Must be only 3 words");
                            System.out.println("Please enter 3 words");
                            three = keyboard.nextLine();
                            tokens = three.split(" ");
                        }
                    } 
                }
        
                public void isNumber()
                {
                    int number;
    
                    System.out.println("Please enter an integer number.");
    
                     boolean doThis = true; 
                     while (doThis == true)
                     {
                         if (keyboard.hasNextInt()) 
                         {                             
                              number = keyboard.nextInt();  
                              System.out.println(number);  
                              doThis = false;
                         }   
                         else 
                	     {
                		    System.out.println("Not an int, try again");                          // Echo user's number back if it is an int
                            System.out.println("Try again");
                            keyboard.nextLine();
                	     }   
                     }
                }
    
                public void isSingle()
                {    
                    String single;
    
                    System.out.println("Please enter a single word");
                    single = keyboard.nextLine();
                    
                    String[] tokens = single.split("\\s+");
                    
                    boolean doSingle = true;
                    while (doSingle == true)
                    {   
                        if (tokens.length == 1 )
                        {
                            System.out.println(single);
                            doSingle = false;
                        }
                        else
                        {
                            System.out.println("You must enter only one word.");
                            System.out.println("Please enter one word.");
                            single = keyboard.nextLine();
                            tokens = single.split("\\s+");
                        }
                    } 
                }
    
                public void isDecimal() 
                {
                    double decimal;
    
                    System.out.println("Please enter a real (decimal) number");
                    
                    boolean doDouble = true;
                    while (doDouble == true)
                    {
                        if (keyboard.hasNextDouble())
                        {
                            decimal = keyboard.nextDouble();
                            System.out.println(decimal);
                            doDouble = false;
                        }
                        else
                        {
                            System.out.println("You must enter a decimal number.");
                            System.out.println("Please enter a real (decimal) number.");
                            keyboard.nextLine();
                        }
                    }
                }
    
                public void isWord()
                {
                    String word;
    
                    System.out.println("Please enter a single word");
                    word = keyboard.nextLine();                               // Saves user's word in String phrase 
    
                    String[] tokens = word.split("\\s+");
    
                    boolean doWord = true;
                    while (doWord == true)
                    {
                        if (tokens.length == 1)
                        {
                            System.out.println(word);
                            doWord = false;
                        } 
                        else
                        {
                            System.out.println("You must enter only one word.");
                            System.out.println("Please enter only one word.");
                            word = keyboard.nextLine();
                            tokens = word.split("\\s+");
                        }      
                    }      
                }
                
                public static void main(String[] args) 
                {
                    Echo echo = new Echo();
                    echo.isPhrase();
                    echo.isThree();
                    echo.isNumber();
                    echo.isSingle();
                    echo.isDecimal();
                    echo.isWord(); 
                }
    }

  2. #2
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,316
    Blog Entries
    1
    Rep Power
    26

    Default Re: Odd bug

    Your problem is with the method prior to isSingle, namely "isNumber()":

    Java Code:
       public void isNumber() {
          int number;
    
          System.out.println("Please enter an integer number.");
    
          boolean doThis = true;
          while (doThis == true) {
             if (keyboard.hasNextInt()) {
                number = keyboard.nextInt();
                System.out.println(number);
                doThis = false;
             } else {
                System.out.println("Not an int, try again"); 
                System.out.println("Try again");
                keyboard.nextLine();
             }
          }
       }
    And the problem is specifically with this line:
    Java Code:
    number = keyboard.nextInt();
    Here your Scanner object, keyboard, gets the nextInt available to it, but it doesn't handle the end of line token which is "swallowed" the next time keyboard.nextLine() is called, and this occurs in the isSingle method. Thus when keyboard.nextLine(); gets called in isSingle() it handles the dangling end of line token which is present, and doesn't give you a chance to enter any text or press return.

    There are several solutions available. The simplest I think is to call keyboard.nextLine() after you get the int so the Scanner object can handle the end of line token. This would change your isNumber method to something like so:


    Java Code:
       public void isNumber() {
          int number;
    
          System.out.println("Please enter an integer number.");
    
          boolean doThis = true;
          while (doThis == true) {
             if (keyboard.hasNextInt()) {
                number = keyboard.nextInt();
                [color="red"][b]keyboard.nextLine(); // *** this swallows the EOL token ***[/b][/color][b][/b]
                System.out.println(number);
                doThis = false;
             } else {
                System.out.println("Not an int, try again"); 
                System.out.println("Try again");
                keyboard.nextLine();
             }
          }
       }
    Another way to handle this is to use keyboard to only get nextLine and either parse the line yourself for int or double, or use another Scanner object to parse the returned String.

  3. #3
    DarrylBurke's Avatar
    DarrylBurke is offline Forum Police
    Join Date
    Sep 2008
    Location
    Madgaon, Goa, India
    Posts
    11,423
    Rep Power
    20

    Default Re: Odd bug

    nextInt() doesn't consume the newline at the end of the input. That remains in the buffer and gets consumed at the next call to nextLine.

    db

    Note to self: refresh the page before posting, especially after tracking down a cross poster

  4. #4
    sunde887's Avatar
    sunde887 is offline Moderator
    Join Date
    Jan 2011
    Location
    Richmond, Virginia
    Posts
    3,069
    Blog Entries
    3
    Rep Power
    8

    Default Re: Odd bug

    When using a boolean variable in some condition you should not be using ==(this won't cause the problem, it's just a problem I notice). == returns boolean, so a boolean variable being compared to another boolean variable is a waste. If you are testing a variable is true, simply type
    Java Code:
    boolean b = true;
    if(b){ ... }
    for false, you use the negation operator '!'

    Java Code:
    boolean b = false;
    if(!b){ ... }

  5. #5
    Join Date
    Sep 2011
    Posts
    18
    Rep Power
    0

    Default Re: Odd bug

    Ah, that makes sense! And that fixed it! I was thinking it had to be something with the tokens, but I kept changing the wrong part.

    Thanks so much!

  6. #6
    Join Date
    Sep 2011
    Posts
    18
    Rep Power
    0

    Default Re: Odd bug

    Quote Originally Posted by sunde887 View Post
    When using a boolean variable in some condition you should not be using ==(this won't cause the problem, it's just a problem I notice). == returns boolean, so a boolean variable being compared to another boolean variable is a waste. If you are testing a variable is true, simply type
    Java Code:
    boolean b = true;
    if(b){ ... }
    for false, you use the negation operator '!'

    Java Code:
    boolean b = false;
    if(!b){ ... }
    Oh ok, thanks for the tip! This is my first Java class, so I still have a lot of problems with syntax.

Posting Permissions

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