我必须拼写一个字扰乱游戏"游戏"我有我需要使用的所有方法。我仍然需要在主要方法中输入代码来询问用户猜测并使用.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();
}
}