1
我必須讓一個字擾頻器「遊戲」,我有我需要使用的所有方法。我仍然需要將代碼放在主要方法中,讓用戶猜測並使用.equals來查看它是否合適。這不是問題。我遇到了一個關於我的scrambleWord(word)方法的問題。我使用了字符串生成器,並不知道如何返回。該代碼看起來不錯,並建立,但說有一個錯誤。誰能幫忙?這是我現在的代碼。麻煩從字符串生成器返回類型的單詞爭奪遊戲的最終方法
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Random;
/**
*
* @author Brian2
*/
public class Project3 {
/**
* @param args the command line arguments
* @throws java.io.IOException
*/
public static void main(String[] args) throws IOException {
//Shuffle s = new Shuffle();
// s.shuffle("hello");
String[] words = createListOfWords();
String word = chooseRandomWord(words);
String scrambledWord = scrambleWord(word);
System.out.println(scrambledWord);
/* code for asking userers guess
*
*use .equals
*
*
*/
}
double[] wordList = new double[65573];
private static String[] createListOfWords() throws FileNotFoundException, IOException {
BufferedReader in = new BufferedReader(new FileReader("wordlist.txt"));
String str;
List<String> list = new ArrayList<String>();
while ((str = in.readLine()) != null) {
list.add(str);
}
String[] stringArr = list.toArray(new String[0]);
// test to see if array stored--System.out.println(Arrays.toString(stringArr));
return stringArr;
}
/**
*
* @param words
* @return
*/
private static String chooseRandomWord(String[] words) {
int index = new Random().nextInt(words.length);
String word = words[index];
return word;
}
private static String scrambleWord(String word) {
char[] charArray = word.toCharArray();
List<Character> characters = new ArrayList<>();
StringBuilder scrambledWord = new StringBuilder(word.length());
int randPicker = (int) (Math.random() * characters.size());
StringBuilder append = scrambledWord.append(characters.remove(randPicker));
/*for (int i = charArray.length - 1; i > 0; i--) {
int j = ((int)(Math.random())(i + 1));
double scrambledWord = charArray[i];
charArray[i] = charArray[j];
charArray[j] = (char) scrambledWord;
}*/
return scrambledWord.toString() ;
/*This method should take a word as an argument, and return the
same word, except scrambled. In order to scramble a word, convert
it to an array of chars, like this:*/
//char[] charArray = word.toCharArray();
}
}
*「代碼看起來不錯,並建立,但說有錯誤。」*它說有什麼錯誤? – 2014-11-07 00:19:19
它說在scrambleWord的主要方法有錯誤,但使用下面的建議解決它,並返回我所需要的。 – 2014-11-07 00:27:09
如果您指的是'IndexOutOfBoundsException'(我必須通過運行代碼並創建自己的'wordlist.txt'來重新創建,因爲您既沒有提供堆棧跟蹤也沒有提供最小的可編譯示例),請查看您的堆棧跟蹤。它會告訴你確切的錯誤在哪裏。在你的情況下,它清楚地標識了你對'scrambleWord'中'.remove(...)'的調用,[記錄爲拋出,如果索引超出範圍](http://docs.oracle.com/javase /7/docs/api/java/util/ArrayList.html#remove(int))。請遵循[這些指導原則](http://meta.stackoverflow.com/a/261593/616460)。 – 2014-11-07 00:28:04