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

Dani AI

Generated

Two separate issues are most likely causing the intermittent "null" outputs: the fallback generator path never assigns a usable string back into the response variable, and the file/blank/EOF checks in the loop are fragile. is correct to flag the random-index bound as a potential off-by-one source, and is right that a chosen index larger than the number of lines will force the fallback—so both concerns should be addressed, but start by verifying what the fallback actually returns or assigns.

Fixes and checks to apply (in order):

  • Confirm that the fallback actually gives response a value. If generateword() returns a String, assign it: response = generateword();. If it mutates a field, make that explicit. Otherwise response can remain null and print as "null".
  • Test for EOF before calling String methods: readLine() returns null at EOF, so check response == null first. After that, use response.trim().isEmpty() to detect blank lines—do not use == to compare string contents.
  • Close resources (try-with-resources) to avoid masking I/O problems.

A simpler, more robust pattern (read small files into memory, then pick a valid random line):

List<String> lines = Files.readAllLines(Paths.get("file.txt"), StandardCharsets.UTF_8);
List<String> nonEmpty = lines.stream().map(String::trim).filter(s -> !s.isEmpty()).collect(Collectors.toList());
String response = nonEmpty.isEmpty() ? generateword() : nonEmpty.get(ThreadLocalRandom.current().nextInt(nonEmpty.size()));

This avoids looping logic errors and ties the random bound to the actual number of usable lines.

Quick debugging tips: log the chosen index and list size before using it, and print the value returned by generateword() to confirm it is non-null. Also inspect usedfile semantics—ensure it is set only after a concrete response is chosen. These steps will identify whether the problem is the random selection, the EOF/blank-line checks, or the fallback not setting response.

Recommended Answers

All 2 Replies

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.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.