让Java程序从数组中选择一个随机字,然后打印字符上方的索引

让Java程序从数组中选择一个随机字,然后打印字符上方的索引,java,arrays,indexing,Java,Arrays,Indexing,我正在尝试创建一个单词解读游戏程序。程序从文本文件中的单词列表中选择一个随机单词,并将它们放入数组中。然后打印出上面有索引号的单词。我似乎无法使索引与所选单词长度匹配。它不断打印文本文件中的每个索引。输出总是10个索引编号,下面有一个较短的单词。如何使额外索引不打印 import java.io.*; import java.util.*; public class Midterm { // class header public static void main(String[]

我正在尝试创建一个单词解读游戏程序。程序从文本文件中的单词列表中选择一个随机单词,并将它们放入数组中。然后打印出上面有索引号的单词。我似乎无法使索引与所选单词长度匹配。它不断打印文本文件中的每个索引。输出总是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->words数组长度,如果要打印单词本身中字母的索引,则for循环应如下所示:

for (int j = 0; j < words[randNum].length(); j++)
    System.out.print(j);
首先选择介于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]);
}