我想实现.nextLine来输入名称,因为如果使用.next,它就不能在空格" aceace"之后存储名称。目前我想使用.nextLine存储" Ace Ace"。但系统一直在为我输入名称,请帮助我。
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");
}
}
答案 0 :(得分:0)
selectOption = scan.nextInt();
输入此行后按回车键,实际上是在输入一行&#39;你的
name = scan.nextLine();
耗尽。为防止这种情况,请在输入您的选择后再添加scan.nextLine()
:
do {
System.out.print(/*whatever*/);
selectOption = scan.nextInt();
scan.nextLine();
} while (/*your condition*/);