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

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

如何停止循環從刪除劊子手的正確猜測?

如何停止循環從刪除劊子手的正確猜測?

qq_笑_17 2022-09-14 10:46:50
以下是海綿這個詞的劊子手問題。當用戶輸入正確的字符(s,p,o,n,g,e)時,數組隱藏[]會正確更新(將_替換為正確的字符)。但是,當用戶輸入不正確的字符時,它會顯示隱藏 [],其中包含所有 _ _ _ _ _ _ _任何提示都值得贊賞!謝謝package javaapplication3;import java.util.Scanner;public class JavaApplication3 {    public static void main(String[] args) {        String secretWord = "sponge";        int lettersLeft = secretWord.length();        int attempts = 6;        int position = 0; //Index of found character in string        char[] hidden = new char[secretWord.length()]; //Array of hidden chars        //Display initial hidden array        for(int i=0; i < secretWord.length(); i++)        {            hidden[i] = '_';            System.out.print(hidden[i] + " ");        }        do{            System.out.println("");            System.out.println("Attempts left = " + attempts);            System.out.println("Enter a letter to guess the word: ");            //User enters character            Scanner scan2 = new Scanner (System.in);            char test = scan2.next().charAt(0);            //Search string secretWord if char test is in it            if(secretWord.contains(Character.toString(test)))            {                position = secretWord.indexOf(test) +1;                //System.out.println("Letter is in position: " + position);                lettersLeft--;            }            else            {                position = 0;                attempts--;            }            //Update hidden array with _ or correct char            for(int i=0; i < secretWord.length(); i++)            {                if (position == 0)                {                    hidden[i] = '_';                }                else if (position != 0)                {                    hidden[position-1] = test;                }                System.out.print(hidden[i] + " ");            }        } 
查看完整描述

1 回答

?
catspeake

TA貢獻1111條經驗 獲得超0個贊

如果輸入不正確,您可以重寫整個數組 - 在顯示其內容的同一循環中。我不知道你為什么這樣做。hidden_


您要做的是只在 中更新正確的猜測,并在不正確的猜測時保持原樣。hidden


例如,替換以下內容:


//Update hidden array with _ or correct char

for(int i=0; i < secretWord.length(); i++)

{

    if (position == 0)

    {

    hidden[i] = '_';

    }

    else if (position != 0)

    {

       hidden[position-1] = test;     

    }

    System.out.print(hidden[i] + " ");

}

與此:


if (position != 0) {

    hidden[position - 1] = test;

}

for (int i = 0; i < secretWord.length(); i++) {

    System.out.print(hidden[i] + " ");

}


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

添加回答

舉報

0/150
提交
取消
微信客服

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

幫助反饋 APP下載

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

公眾號

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