Welcome to the Java Programming Forums


The professional, friendly Java community. 21,500 members and growing!


The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.


>> REGISTER NOW TO START POSTING


Members have full access to the forums. Advertisements are removed for registered users.

Results 1 to 7 of 7

Thread: Why do I have to create a new Scanner?

  1. #1
    Junior Member
    Join Date
    Oct 2012
    Posts
    3
    My Mood
    Cheeky
    Thanks
    1
    Thanked 0 Times in 0 Posts

    Default Why do I have to create a new Scanner?

    I'm have just begun learning java and have been asked to create a program which:

    Assigns 2 Arrays: Suit, Rank
    Uses the Math.random class to determine the cards drawn. (I realize that this isn't a very realistic approach to how cards are drawn.)
    I ran into troubles when I tried to add the option for the user to choose to draw a new hand.
    For some reason the compiler will run, but when I go to ask for a new hand I get the message: "static error: undefined name 'yes' "

    My Code before fix


    import java.util.Scanner;
     
    public class exercise5{
      public static void main(String[] args){
        Scanner input = new Scanner(System.in);
        String again;
     
        do{
          System.out.println("How many cards would you like?");
          int counter = input.nextInt();
     
          String[] suit = {"Diamonds", "Clubs", "Hearts", "Spades"};
          String[] rank = {"Ace", "King", "Queen", "Jack", "10", "9", "8", "7", "6", "5", "4", "3", "2", "1"};
     
          while (counter > 0){
     
            double rand1 = Math.random() * 4;
            int ran1 = (int)rand1;
            double rand2 = Math.random() * 14;
            int ran2 = (int)rand2;
     
            if (rand1 >= 3.9 || rand2 >= 13.9)
              System.out.println("You got a joker!!!");
     
            else
              System.out.println(rank[ran2]+ " of " + suit[ran1]);
     
          counter --;
          }
     
     
        System.out.println("Would you like a new hand? ");
        again = input.nextLine();
     
        }while (again.startsWith("y") || again.startsWith("Y"));
      }
    }

    I have found that assigning a new Scanner just before my do-while condition will fix my program. I am looking for a reason as to why. I'm not sure I understand what is happening. If anyone could help me out, it would be greatly appreciated.


    My Code After Fix

    import java.util.Scanner;
     
    public class exercise5{
      public static void main(String[] args){
        Scanner input = new Scanner(System.in);
        String again;
     
        do{
          System.out.println("How many cards would you like?");
          int counter = input.nextInt();
     
          String[] suit = {"Diamonds", "Clubs", "Hearts", "Spades"};
          String[] rank = {"Ace", "King", "Queen", "Jack", "10", "9", "8", "7", "6", "5", "4", "3", "2", "1"};
     
          while (counter > 0){
     
            double rand1 = Math.random() * 4;
            int ran1 = (int)rand1;
            double rand2 = Math.random() * 14;
            int ran2 = (int)rand2;
     
            if (rand1 >= 3.9 || rand2 >= 13.9)
              System.out.println("You got a joker!!!");
     
            else
              System.out.println(rank[ran2]+ " of " + suit[ran1]);
     
          counter --;
          }
     
     
        Scanner in = new Scanner(System.in);
        System.out.println("Would you like a new hand? ");
        again = in.nextLine();
     
        }while (again.startsWith("y") || again.startsWith("Y"));
      }
    }


  2. #2
    Super Moderator pbrockway2's Avatar
    Join Date
    Jan 2012
    Posts
    939
    Thanks
    6
    Thanked 202 Times in 178 Posts

    Default Re: Why do I have to create a new Scanner?

    I don't think the compiler message comes from the code you posted (which does not contain the symbol 'yes' referred to in the message).

    Both version of the code compile as they are.

  3. #3
    Member
    Join Date
    Jun 2012
    Location
    Left Coast, USA
    Posts
    451
    My Mood
    Mellow
    Thanks
    1
    Thanked 97 Times in 88 Posts

    Default Re: Why do I have to create a new Scanner?

    Quote Originally Posted by Currahe View Post
    I'm have just begun learning java and have been asked to create a program which:

    Assigns 2 Arrays: Suit, Rank
    Uses the Math.random class to determine the cards drawn. (I realize that this isn't a very realistic approach to how cards are drawn.)
    I ran into troubles when I tried to add the option for the user to choose to draw a new hand.
    For some reason the compiler will run, but when I go to ask for a new hand I get the message: "static error: undefined name 'yes' "

    My Code before fix

    .
    .
    .
    That's funny. (I mean "funny-peculiar," not "funny-haha.")

    When I run your first example, it asks "How many cards..." and when I enter an integer, it deals the cards and then quits without asking for anything else.

    Here's the deal (Is it possible for you to pardon the pun? Sometimes I just can't help myself.)

    When the user types a bunch of stuff and then presses 'Enter' all of the characters are in a system buffer and a special line termination character is appended. (A "newline" character, if you will.)

    Then when the program executes the nextInt() method, the scanner builds an integer from characters in the system buffer, and stops scanning when it sees the 'newline' character. The 'newline' character is still in the system buffer at this point.

    If the user had entered some integer digits and a space and some other stuff, all of the other stuff would still be in the input buffer..

    Anyhow...

    When the program executes the nextLine() method, the Scanner starts with whatever is left in the buffer from any previous calls to nextInt(), and the Scanner stops when it sees a 'newline' character. The effect is that if the user enters an integer and the program executes nextInt(), the nextLine() method sees the 'newline' character, removes it from the buffer and returns with an empty String. (If the input buffer is empty when a nextLine() is executed, the Scanner will wait for user input and then retrieve characters until it sees the 'newline' character. Note that the 'newline' character encountered by nextLine() will be removed from the input buffer, but will not appear in the String.

    It's easy to avoid that by simply putting a "dummy" nextLine() immediately after the nextInt() instruction so that the nextLine() will see an empty buffer and will wait for further input.

    So...

    Maybe you can go back to the first example code in your post and make the following change:

          System.out.println("How many cards would you like?");
          int counter = input.nextInt();
          input.nextLine(); // "Dummy input flushes the input buffer and throws away any detritus

    Much cleaner than creating a brand new Scanner, right?


    Cheers!

    Z
    Last edited by Zaphod_b; October 18th, 2012 at 02:34 PM.

  4. The Following User Says Thank You to Zaphod_b For This Useful Post:

    Currahe (October 18th, 2012)

  5. #4
    Junior Member
    Join Date
    Oct 2012
    Posts
    3
    My Mood
    Cheeky
    Thanks
    1
    Thanked 0 Times in 0 Posts

    Default Re: Why do I have to create a new Scanner?

    Oh, well maybe it is just the compiler I am using... are you using Dr. Java?

  6. #5
    Super Moderator pbrockway2's Avatar
    Join Date
    Jan 2012
    Posts
    939
    Thanks
    6
    Thanked 202 Times in 178 Posts

    Default Re: Why do I have to create a new Scanner?

    are you using Dr. Java?
    No, I just compiled with javac.

  7. #6
    Member
    Join Date
    Jun 2012
    Location
    Left Coast, USA
    Posts
    451
    My Mood
    Mellow
    Thanks
    1
    Thanked 97 Times in 88 Posts

    Default Re: Why do I have to create a new Scanner?

    Quote Originally Posted by Currahe View Post
    Oh, well maybe it is just the compiler I am using... are you using Dr. Java?
    If I am the one you are asking, the answer is no.

    For testing I used command line compile with javac and command line execution with java (OpenJDK Java version 1.6.0_22) on a Centos 5.8 Linux workstation.



    Did you try your original code with the "dummy" nextLine() added, as I suggested/recommended?


    Cheers!

    Z
    Last edited by Zaphod_b; October 18th, 2012 at 02:28 PM.

  8. #7
    Junior Member
    Join Date
    Oct 2012
    Posts
    3
    My Mood
    Cheeky
    Thanks
    1
    Thanked 0 Times in 0 Posts

    Thumbs up Re: Why do I have to create a new Scanner?

    Thank you, i am very grateful for your explanation. Your solution is very useful as well, I will remember to keep it in mind. Like I said, I'm new to programming, and my teacher wasn't able to answer this for me, so thank god for this forum. lol Thanks again.
    Last edited by Currahe; October 30th, 2012 at 03:00 PM.

Similar Threads

  1. scanner and int issue
    By saintnicks in forum What's Wrong With My Code?
    Replies: 3
    Last Post: August 24th, 2012, 01:01 AM
  2. How to use Scanner for files?
    By Shwetaa in forum Java Theory & Questions
    Replies: 1
    Last Post: September 9th, 2011, 07:53 PM
  3. Scanner help
    By sp11k3t3ht3rd in forum Java Theory & Questions
    Replies: 3
    Last Post: June 22nd, 2011, 11:55 AM
  4. Scanner vs BufferedReader?
    By Bill_H in forum File I/O & Other I/O Streams
    Replies: 11
    Last Post: October 27th, 2009, 09:44 AM
  5. Help With Scanner
    By jtphenom in forum File I/O & Other I/O Streams
    Replies: 1
    Last Post: October 12th, 2009, 08:49 PM