Why the console said Index 0 out of bounds for length 0
?
It says in my method CharacterSearch()
.
这是我的代码.顺便说一下,代码是Hangman Game.我对Java是个新手,并不了解所有的库.
package besingaPi_LE_3_2;
import java.util.Scanner;
public class GameHangman {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int miss = 0;
String choice1;
String temp;
String[] words = {"giraffe", "hipopotamus", "gorilla", "peacock", "armadillo"};
int choice;
//do {
mainMenu();
choice = input.nextInt();
System.out.println();
if(choice == 1){
String wordRandom = Randomizer(words);
// char[] letters = new char[wordRandom.length()];
String mute = secretWord(wordRandom);
temp = mute;
// char c = wordRandom.charAt(3);
// System.out.println(c);
System.out.println(wordRandom);
System.out.println("Note: use only small character/s");
while(!mute.equals(wordRandom)) {
System.out.print("(Guess) Enter a letter in word " + mute + " > ");
choice1 = input.nextLine();
// char letter = choice1.charAt(0);
mute = CharacterSearch(wordRandom, mute, choice1);
if(temp.equals(mute)) {
miss++;
}
temp = mute;
}
System.out.println("The word is " + wordRandom + "." + " You missed " + miss + " time.");
}
else if (choice == 0) {
System.out.println("Thank you!!");
return;
}
}
public static void mainMenu() {
System.out.println("Welcome to Hangman");
System.out.println("[1]START\n[0]EXIT");
System.out.print("Please input your choice: ");
return;
}
public static String CharacterSearch(String word, String muted, String key) {
StringBuilder update = new StringBuilder(muted);
int i;
for(i = 0; i < word.length(); i++) {
if(word.charAt(i) == key.charAt(0)) {
update.setCharAt(i,key.charAt(0));
}
}
muted = update.toString();
return muted;
}
public static String secretWord(String word) {
String temp = "";
for(int i = 0; i < word.length(); i++) {
temp += "*";
}
return temp;
}
public static String Randomizer(String[] words) {
int rand = (int)(Math.random() * words.length);
String word = words[rand];
return word;
}
}
我try 了这么多东西,但它总是会说Index Out Out.