随机读取数组

时间:2012-11-15 21:38:43

标签: java

我有一个节目&我不会随机读取ARRAY我没有程序错误  但在输出期间,我有空值,你能给我解决方案......

import java.io.FileInputStream;
import java.util.Properties;
import java.util.Random;
import javax.swing.JOptionPane;

public class ReadDB {
    public static void main(String[] args) {

        Properties prob = new Properties();
        String word [] = new String [20] ;
        try{
            prob.load( new FileInputStream("words.txt"));
        }catch(Exception e){
        }
        for(int i=1; i<6; i++){         
            String temp = prob.getProperty(""+i);
            word[i] = temp;
            Random ran = new Random ();

            String Val = word[ran.nextInt(word.length)];

            System.out.println(Val);

        }
    }
}

3 个答案:

答案 0 :(得分:5)

您的数组长度为20,而您只填充5个值:for(int i=1; i<6; i++){。这解释了空值。

答案 1 :(得分:2)

  1. 您的数组大小为20,但您的循环只有5次迭代。
  2. 你的循环开始于错误的索引(部分相关)
  3. 您正在对word数组进行随机轮询,然后才能实际填充数据:
  4. 从以下位置更改:

    for(int i=1; i<6; i++){         
        String temp = prob.getProperty(""+i);
        word[i] = temp;
        Random ran = new Random ();
        String Val = word[ran.nextInt(word.length)];
        System.out.println(Val);
    }
    

    要:

    for(int i=0; i<20; i++){         
        String temp = prob.getProperty(""+i);
        word[i] = temp;
    }
    
    for(int i=0; i<20; i++){
        Random ran = new Random ();
        String Val = word[ran.nextInt(word.length)];
        System.out.println(Val);
    }
    

答案 2 :(得分:0)

您的输出可能为null,因为prob.getProperty为随机选择的索引的键返回null,但问题更可能是随机生成的索引超出了正在填充的5个值的范围。

两条建议:

  1. 永远不要忽略异常。最有可能的是,prob由于异常而无法加载。而是打印例外:e.printStackTrace()

  2. 确保您加载的预期属性实际上具有填充words数组时假设存在的密钥1-5。