我正在尝试创建一个单词解读游戏程序。程序从文本文件中的单词列表中选择一个随机单词并将它们放入一个数组中。然后打印出上面带有索引号的单词。我似乎无法使索引与所选单词长度相匹配。它不断打印出文本文件中的每个索引。输出总是10个索引号,下面有一个较短的单词。如何让额外的索引无法打印?
import java.io.*;
import java.util.*;
public class Midterm { // class header
public static void main(String[] args) { // Method header
String[] words = readArray("words.txt");
/*
* Picks a random word from the array built from words.txt file. Prints
* index with word beneath it.
*/
int randNum = (int) (Math.random() * 11);
for (int j = 0; j < words.length; j = j + 1) {
System.out.print(j);
}
System.out.print("\n");
char[] charArray = words[randNum].toCharArray();
for (char c : charArray) {
System.out.print(c);
}
}
// end main
public static String[] readArray(String file) {
// Step 1:
// Count how many lines are in the file
// Step 2:
// Create the array and copy the elements into it
// Step 1:
int ctr = 0;
try {
Scanner s1 = new Scanner(new File(file));
while (s1.hasNextLine()) {
ctr = ctr + 1;
s1.nextLine();
}
String[] words = new String[ctr];
// Step 2:
Scanner s2 = new Scanner(new File(file));
for (int i = 0; i < ctr; i = i + 1) {
words[i] = s2.next();
}
return words;
} catch (FileNotFoundException e) {
}
return null;
}
}
答案 0 :(得分:0)
你的循环是0 - &gt;单词数组长度,如果你想打印单词本身中字母的索引,那么你的for循环应该是这样的:
for (int j = 0; j < words[randNum].length(); j++)
System.out.print(j);
答案 1 :(得分:0)
首先选择0到words.length - 1之间的randNum
随机数,然后您可以使用words[randNum]
访问该单词。
简化版:
public static void main(String[] args) { // Method header
String[] words = readArray("words.txt");
/*
* Picks a random word from the array built from words.txt file. Prints
* index with word beneath it.
*/
//Choose random number between 0 to words.length - 1
int randNum = new Random().nextInt(words.length);
for (int j = 0; j < words[randNum].length(); j = j + 1) {
System.out.print(j);
}
System.out.print("\n");
System.out.println(words[randNum]);
}