0

I've a program & I wont to read ARRAY randomly I don't have error with program but during output I have null value can you give me the solution ...

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 Answers 3

5

Your array has a length of 20 and you are filling only 5 values: for(int i=1; i<6; i++){. That explains null values.

Sign up to request clarification or add additional context in comments.

Comments

2
  1. Your array has size 20 but your loop has only 5 iterations.
  2. Your loop starts at the wrong index (partially related)
  3. You are doing the random polling of the word array before it's actually finished being populated with data:

Change it from:

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);
}

To:

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 Comments

i changed now but a some time i have null but less than before can i use while before second for loop
@rawaztariq you can try, but as others have pointed out, the bigger issue is how you are actually getting the string for temp.
0

Your output could null because prob.getProperty is returning null for the key of the randomly selected index, but more likely the issue is that the randomly generated index is outside the range of 5 values being filled.

Two recommendations:

  1. Never ignore exceptions. Most likely, prob is failing to be loaded due to an exception. Instead, print the exception: e.printStackTrace().

  2. Ensure that your expected properties being loaded actually have the keys 1-5 that you assume exist in filling your words array.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.