Sorry for the long code. Here it loops through a text file with up to 5 lines and reads a random line. If the line it reads is null then it generates a random response. However when compiled with a test file of 2 lines it only has an output 2/5 of the time - when it reads from the text file. The other times it prints null. As you caqn see I have tried many ideas in the if statement but nothing seems to work.

int check_phrase = (int) (Math.random()*4);
                //reads file lines until chosen line is found
                                    try {
                    BufferedReader r = new BufferedReader(new FileReader(f));
                    boolean check =false;

                    int c = 0;
                            while(!check){
                                response = r.readLine();

                                c++;

                                //if the text file is too short then generate a response
                                if(response == "" || response == "\n" || response == null){
                                    generateword();
                                    check = true;
                                }else{
                                    usedfile = true;
                                }


                                if(c>=check_phrase){
                                    check = true;
                                }
                            }




                    }
                 catch (IOException e) {
                    generateword();
                }

Hi there!

I've tested your code and come up with the following:

  1. You might want to check your random values. According to Oracles documentation, Math.random() does the following:
    Returns a double value with a positive sign, greater than or equal to 0.0 and less than 1.0.
    Less than 1.0 means that your maximum values will be less than 4. And by converting your double to int using (int) you simply cut all decimals, thus your maximum value will be 3. This means that you will only read at most 4 lines (0-3). A suggestion is to use:

    Random rnd = new Random(); // Do this once, generates a unique seed
    int myVal = rnd.nextInt(5); // Generates an integer [0, 4]
    
  2. I think what's actually causing your problem is that you increase c before checking if it's bigger or equal to check_phrase.

Regards,
Emil Olofsson

If the file is smaller than the random number then it wont matter.

This article has been dead for over six months. Start a new discussion instead.