user2603506
user2603506

Reputation: 23

How to use the Scanner class properly?

I'm doing an assignment for class. For some reason the program completely skips the part where the variable name is supposed to be typed in by the user. I can't think of any reason why it's behaving this way, since the rest of my code that is after the cardType part (which asks for things such as String and int types work fine and in order.

        System.out.println("Enter the card information for wallet #" + 
                                    (n+1) + ":\n---\n");
        System.out.println("Enter your name:");
        String name = scan.nextLine();
        name = capitalOf(name);
        System.out.println("Enter card type");
        String cardType = scan.nextLine();
        cardType = capitalOf(cardType);

Upvotes: 1

Views: 108

Answers (2)

user3437460
user3437460

Reputation: 17454

It is behaving this way because I am quite sure you used the same scanner object to scan for integers/double values before you used it to scan for name.

Having said that does not mean you have to create multiple scanner objects. (You should never do that).

One simple way to over come this problem is by scanning for strings even if you are expecting integers/doubles and cast it back.

Scanner scn = new Scanner(System.in);
int numbers = scn.nextInt();  //If you do this, and it skips the next input
scn.nextLine();  //do this to prevent skipping 

//I prefer this way
int numbers = Integer.toString(scn.nextLine());
String str = scn.nextLine();    //No more problems

Upvotes: 1

Eran
Eran

Reputation: 393841

You probably need to consume the end of the last line you read prior to trying to get the user name :

    scan.nextLine(); // add this
    System.out.println("Enter the card information for wallet #" + 
                                (n+1) + ":\n---\n");
    System.out.println("Enter your name:");
    String name = scan.nextLine();
    name = capitalOf(name);
    System.out.println("Enter card type");
    String cardType = scan.nextLine();
    cardType = capitalOf(cardType);

Upvotes: 1

Related Questions