亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如何編寫Do/While驗證?

如何編寫Do/While驗證?

白衣非少年 2022-09-01 18:05:48
我目前正在學習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"));

你可以在最后為“是”/“否”做同樣的事情。


我認為你在這方面做得很好。


查看完整回答
反對 回復 2022-09-01
  • 1 回答
  • 0 關注
  • 158 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號