用*替换字母

时间:2015-09-13 09:41:57

标签: java replace indexof

制作刽子手风格的游戏

我现在有一个随机的词。如何用星号*替换单词的字母,以便在程序启动时单词显示为*。

我假设当有人为刽子手游戏输入一封信时,你会得到该单词中该字符的索引,然后替换相应的*。

public class JavaApplication10 {

public static String[] wordArray = new String[1];
public static String file_dir = "Animals.txt";
public static String selectedWord = "";
public static char[] wordCharacter = new char[1];
Scanner sc = new Scanner(System.in);

public static void main(String[] args) throws IOException {
    wordArray = get_word(file_dir);
    selectedWord = select_word(wordArray);

    System.out.println(selectedWord);  
}

public static String[] get_word(String file_dir) throws IOException {
    FileReader fileReader = new FileReader(file_dir);
    BufferedReader bufferedReader = new BufferedReader(fileReader);
    List<String> lines = new ArrayList<String>();
    String line = null;
    while ((line = bufferedReader.readLine()) != null) {
        lines.add(line);
    }
    bufferedReader.close();
    return lines.toArray(new String[lines.size()]);
}

public static String select_word(String[] wordArray) {
    Random rand = new Random();
    int lines = Math.abs(rand.nextInt(wordArray.length)- 1);
    return wordArray[lines];
}

}

2 个答案:

答案 0 :(得分:0)

如果你知道有多少行,你可以使用Random method in java with a specific range to pick out a line at random

然后你可以逐行读取文件,直到你到达那个随机行并打印出来。

// Open the file
FileInputStream fstream = new FileInputStream("testfile.txt");
BufferedReader br = new BufferedReader(new InputStreamReader(fstream));

String strLine;
int counter=0;

//While-loop -> Read File Line By Line till the end of file
//And will also terminate when the required line is printed 
while ((strLine = br.readLine()) != null && counter!=randomValue){
    counter++;

    //You need to set randomValue using the Random method as suggested
    if(counter==randomValue)
        // Print the content on the console
        System.out.println (strLine+"\n");
}

//Close the input stream
br.close();

答案 1 :(得分:0)

假设Java 8:

// Loading ...
Random R = new Random(System.currentTimeMillis());
List<String> animals = Files.readAllLines(Paths.get(path));

// ...
// When using
String randomAnimal = animals.get(R.nextInt(animals.size()));