[英]Java: Adding a user input to while loop
我試圖在 PlayerOne class 中放置一個 while 循環,用戶可以在其中選擇玩家的職業。 我不知道如何讓它工作。 你能給我一個建議或提示嗎? 謝謝,(我想您不需要 Player class 或 Main 類,所以我將它們放在一邊)
Scanner scanner = new Scanner(System.in);
while (true) {
System.out.println("Choose your profession: \n" +
"Press 1 for a knight class\n" +
"Press 2 for a rider class\n" +
"Press 3 for a mage class");
int choice = scanner.nextInt();
scanner.nextLine();
switch (choice) {
case 0:
// here I want to put an option to choose a knight by pressing number 1
break;
case 1:
// an option to choose a rider by pressing number 2
break;
case 1:
// an option to choose a mage by pressing number 3
break;
我認為當有人選擇有效職業時,您需要一個停止條件,如下所示:
Scanner scanner = new Scanner(System.in);
String profession = null;
while (profession == null) {
System.out.println("Choose your profession: \n" +
"Press 1 for a knight class\n" +
"Press 2 for a rider class\n" +
"Press 3 for a mage class");
int choice = scanner.nextInt();
scanner.nextLine();
switch (choice) {
case 1:
profession = "knight";
break;
case 2:
profession = "rider";
break;
case 3:
profession = "mage";
break;
default:
System.out.println("Invalid option");
profession = null;
break;
}
}
System.out.println("You selected: "+profession+" class.");
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
String profession= null;
while (profession == null) {
System.out.println("Choose your profession: \n" +
"Press 1 for a knight class\n" +
"Press 2 for a rider class\n" +
"Press 3 for a mage class");
String choice = scanner.nextLine();
if (choice.equals("1")){
profession = "knight";
System.out.println("You selected: "+profession+" class.");
}else if (choice.equals("2")){
profession = "rider";
System.out.println("You selected: "+profession+" class.");
}else if (choice.equals("3")){
profession = "mage";
System.out.println("You selected: "+profession+" class.");
}else {
System.out.println("invaild option");
}
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.