[英]Switch statment within Loop not working correctly
Java的新手,我的代碼遇到麻煩,它是while循環中的switch語句。 我喜歡使用字母或“ char”而不是帶數字的情況“ int”,並且我要退出'q'。 感謝您的輸入。 這是主要代碼。
import java.util.Scanner;
import java.util.*;
public class supraCritters {
public static void main(String [] arguments) {
Critter nastybat = new Critter();
nastybat.health = 100;
nastybat.mood = 50;
nastybat.hunger = 25;
System.out.println("Your critter has just been born,");
System.out.println("here are the stats of your critter.");
nastybat.checkStats();
System.out.println("\nPlease choose a letter");
System.out.println("[c]heck stats \n[f]eed \n[p]lay \n[r]ead \n[t]rain");
System.out.println("[q]uit");
Scanner sChoice = new Scanner(System.in);
char choice = ' ';
while (choice != 'q') {
switch (choice) {
case 'c':
nastybat.checkStats();
break;
case 'f':
nastybat.feed();
break;
case 'p':
nastybat.play();
break;
case 'r':
nastybat.read();
break;
case 't':
nastybat.train();
break;
case 'q':
System.out.println("good bye");
break;
default:
System.out.println("invalid entry");
break;
}
choice = sChoice.next().charAt(0);
}
}
}
當我輸入相應的字母時,循環不顯示輸入法或重復輸入,並且'q'不執行任何操作。 默認情況下,輸入前顯示“無效條目”。
代碼已編輯,仍然有問題。
第一次只能輸入一次! 因此,循環始終返回相同的結果。 您應該在循環內復制獲取輸入的代碼!
Scanner sChoice = new Scanner(System.in);
char choice = '';
while (choice != 'q') {
switch (choice) {
case 'c':
nastybat.checkStats();
break;
.
.
.
.
.
choice = sChoice.next().charAt(0);
第一行獲取第一個開關運行的輸入,循環內的其余行獲取輸入。
更新:
choice = sChoice.next().charAt(0);
應該放在循環的最后,如果不是,如@proskor所說,當用戶點擊“ q
”時,程序將返回“ invalid entry
”。
我完成了代碼,它似乎可以正常工作。 測試對象現在可以使用的方法。
最后
import java.util.Scanner; import java.util.*; public class supraCritters { public static void main(String [] arguments) { Critter nastybat = new Critter(); nastybat.health = 100; nastybat.mood = 50; nastybat.hunger = 25; System.out.println("Your critter has just been born,"); System.out.println("here are the stats of your critter."); nastybat.checkStats(); Scanner sChoice = new Scanner(System.in); char choice = ' '; while (choice != 'q') { switch (choice) { case 'c': case 'C': nastybat.checkStats(); break; case 'f': case 'F': nastybat.feed(); break; case 'p': case 'P': nastybat.play(); break; case 'r': case 'R': nastybat.read(); break; case 't': case 'T': nastybat.train(); break; case 'q': case 'Q': System.out.println("good bye"); break; default: System.out.println("invalid entry"); break; } System.out.println("\\nPlease choose a letter"); System.out.println("[c]heck stats \\n[f]eed \\n[p]lay \\n[r]ead \\n[t]rain"); System.out.println("[q]uit"); choice = sChoice.next().charAt(0); } } }
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.