0

I would like to implement the .nextLine for input the name, because if using .next, it can't store the name after a space "aceace". Currently i want to use .nextLine to store "Ace Ace". But the system keep skipping the name for me to enter, please help me up.

import java.util.Scanner;

/**
*
* @author Dell
*/
public class NewMain {

static final Scanner scan = new Scanner(System.in);
static int selectOption;
private static String name;
static int questionSize = 1;

/**
 * @param args the command line arguments
 */
public static void main(String[] args) {

    do {
        System.out.print("\nPlease select an option: \n"
                + "1. Play Game"
                + "\n2. Maintain Race Path"
                + "\n3. Maintain Question"
                + "\n4. Exit"
                + "\n\nPlease select an option: ");
        selectOption = scan.nextInt();
    } while (selectOption != 1 && selectOption != 2 && selectOption != 3 && selectOption != 4);
    if (selectOption == 4) {
        System.exit(0);

    } else if (selectOption == 1) {

        System.out.print("\nPlease Enter your name: ");
        name = scan.nextLine();  <---------- Here is my input, but system skipped it
        System.out.println();
        setGameDifficulty();
    }

}

static void setGameDifficulty() {
    System.out.println();
    System.out.print("\nChoose difficulty: \n" + "1. Easy\n" + "2. Normal\n" + "3. Hard\n\nChoose: ");
    int difficulty = scan.nextInt();
    scan.nextLine();
    if (difficulty == 1) {
        questionSize = 2;
    } else if (difficulty == 2) {
        questionSize = 3;
    } else {
        questionSize = 5;
    }
    System.out.println("\n");

}
 }
Ling Kit II
  • 3
  • 1
  • 7

1 Answers1

0
selectOption = scan.nextInt();

When you press the return key after inputting for this line, you are in fact inputting a 'line' which your

name = scan.nextLine();

uses up. To prevent that, put another scan.nextLine() after inputting your choice, as such:

do {
    System.out.print(/*whatever*/);
    selectOption = scan.nextInt();
    scan.nextLine();
} while (/*your condition*/);
Anindya Dutta
  • 1,904
  • 2
  • 14
  • 31