我有一个节目&我不会随机读取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);
}
}
}
答案 0 :(得分:5)
您的数组长度为20,而您只填充5个值:for(int i=1; i<6; i++){
。这解释了空值。
答案 1 :(得分:2)
word
数组进行随机轮询,然后才能实际填充数据:从以下位置更改:
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个值的范围。
两条建议:
永远不要忽略异常。最有可能的是,prob
由于异常而无法加载。而是打印例外:e.printStackTrace()
。
确保您加载的预期属性实际上具有填充words
数组时假设存在的密钥1-5。