我正在嘗試撰寫一個代碼來玩劊子手,它作業正常,但每次我輸入一個字符時,它都會重置我的輸出。有人可以幫忙嗎。
我的代碼:
import java.util.*;
public class game
{
public static void main(String args[]) {
Scanner in = new Scanner(System.in);
String list[] = {"apple", "banana", "mango", "kiwi", "coconut", "papaya", "lichi", "strawberry", "orange", "cherry"};
int rand = (int)(Math.random()*9) 0;
String word = list[rand];
String ask = "_";
for(int i = 1; i < word.length();i ){
ask = ask "_";
}
System.out.println(ask);
System.out.println("hint: It is a fruit");
for (int j = 1; j<=15; j ){
System.out.println("Enter a character: ");
char input = in.next().charAt(0);
for (char i : word.toCharArray()){
if(input == i){
System.out.print(input);
continue;
}
System.out.print("_");
}
}
}
}
一小部分輸出:
______
hint: It is a fruit
Enter a character:
a
__a___
Enter a character:
o
o_____
Enter a character:
r
_r____
Enter a character:
n
___n__
Enter a character:
當我輸入“a”時,它會正確列印,但是當我輸入其他字符時,它會列印該字符而不是“a”。有人可以告訴我我該怎么做才能獲得正確的輸出。
uj5u.com熱心網友回復:
看起來您沒有保存添加到游戲中的字符的字串,您只是在列印它。您可能希望執行一些操作,例如將新字符添加到字串變數 _ask 中,而不是邊走邊列印,然后在 for 回圈運行后列印。基本上你不會在任何地方存盤過去的回合。
uj5u.com熱心網友回復:
正如另一個答案中提到的,您需要記住以前嘗試中的字符。例如,這可以像這樣完成:
String tempAsk = "";
for (char i : word.toCharArray()){
if(input == i){
tempAsk = i;
} else {
tempAsk = ask.charAt(i);
}
}
ask = tempAsk;
System.out.println(ask);
uj5u.com熱心網友回復:
我認為,在回圈中for (char i : word.toCharArray()),
您應該將字符添加到ask(或具有另一個名為 的字串變數ans),
然后ask在回圈結束時列印
因為您沒有更新 ask 的值并列印字串中字符的位置,并且當回圈第二次運行時,它不會顯示您輸入的最后一個字符
此外,您可以使用開關盒根據水果名稱獲得特定提示
并且當玩家輸入錯誤的字符時可能會彈出錯誤
uj5u.com熱心網友回復:
您可以使用字符陣列來檢查到目前為止存在哪些字母,如下所示:
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
String list[] = {"apple", "banana", "mango", "kiwi", "coconut", "papaya", "lichi", "strawberry", "orange", "cherry"};
int rand = (int)(Math.random()*9) 0;
String word = list[rand];
// Create a character array to store the result so far
char[] result = new char[word.length()];
//Fill the array with _
Arrays.fill(result, '_');
System.out.println(new String(result));
System.out.println("hint: It is a fruit");
int numChances = 15;
for (int j = 1; j <= numChances; j ){
System.out.println("Enter a character: ");
char input = in.next().charAt(0);
for (int i = 0; i < word.length(); i ) {
if(word.charAt(i) == input){
//update the array with user's correct response
result[i] = input;
}
}
// Check how we're doing so far. Make a string with the result
String untilNow = new String(result);
// Show user what we have so far
System.out.println(untilNow);
//Check if the user has guessed the word.
if(untilNow.equalsIgnoreCase(word)) {
System.out.println("You win...");
break;
}
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/334814.html
