我目前正在學習Java課程的入門課程,我真的很想改進,但我正在努力完成這個任務。任務的要求是實現一個循環,該循環允許用戶通過鍵入 yes 繼續玩游戲。跟蹤用戶:使用遞增變量進行的勝利,損失和游戲當用戶不再希望繼續時,打印其結果,顯示跟蹤的變量:贏、輸和玩過的游戲實施輸入驗證循環以確保用戶輸入正確的輸入(h、t、H、T)我相信除了最后一個之外,我已經完成了所有操作,我已經嘗試了無數次使用do和while循環,但我得到的最接近的是錯誤的輸入循環,而正確的輸入將繞過所有其他if/while/else語句。如果可能的話,我會非常感謝有人看看我的代碼,并解釋我可以做得更好的地方,以及我如何完成或接近最后一個要求。public static void main(String[] args) { Scanner scan = new Scanner(System.in); String input, inputUpper; char userGuess; char coinFlip; int randNum; int wins = 0; int losses = 0; int total = 0; String choice = "yes"; do { System.out.print("I will flip a coin guess 'H' for heads or 'T' for tails --> "); input = scan.nextLine(); inputUpper = input.toUpperCase(); userGuess = inputUpper.charAt(0); randNum = (int) (Math.random() * 2); if(randNum == 0) { coinFlip = 'H'; } else { coinFlip = 'T'; } System.out.println("\nYou picked " + userGuess + " and the coin flip was " + coinFlip + " so ..."); if(userGuess == coinFlip) { System.out.println("You win!"); wins ++; total ++; } else { System.out.println("Better luck next time ..."); losses ++; total ++; } System.out.println("Do you want to continue(yes/no)?"); choice=scan.nextLine(); } while(choice.equalsIgnoreCase("yes")); System.out.println("Thank you for playing."); System.out.println("You guessed correctly this many times: " +wins); System.out.println("You guessed incorrectly this many times: " +losses); System.out.println("During this session you've played this many games: " +total); }}我希望程序需要T / t或H / h才能繼續,如果用戶輸入了不正確的字母或數字,它將要求他們輸入t或h。
1 回答
繁星淼淼
TA貢獻1775條經驗 獲得超11個贊
以下是驗證輸入的簡單方法:
do {
System.out.print("I will flip a coin guess 'H' for heads or 'T' for tails --> ");
input = scan.nextLine();
inputUpper = input.toUpperCase();
} while (!inputUpper.equals("T") && !inputUpper.equals("F"));
你可以在最后為“是”/“否”做同樣的事情。
我認為你在這方面做得很好。
添加回答
舉報
0/150
提交
取消
