1

The code is supposed to take a text file, and put it's contents (phrases) line by line into a phrase array. Then using a random index, select a random phrase from the phrase array. The problem is that the scanner does not read from the text file and returns "null".

  public static String phrasePicker()throws IOException{

                  Scanner input = new Scanner(new File ("Phrases.txt")); 
                  String [] phrases = new String [140];
                  int i = 0;
    //checks if there is a next line in the text file
                  while(input.hasNext()) {
    //if there is a text file, put that line as the index "i" of the array
                    phrases[i] = input.nextLine();
                    i= i++;
                  }
                  Random random = new Random();
                  int select = random.nextInt(phrases.length);
                  String phrase = phrases[select]; 
                  return phrase;
                }
Kavin Zhu
  • 11
  • 1
  • 2
    `i=i++;` should be either `i++;` or `i=i+1;` – Jim Garrison Jan 06 '18 at 04:43
  • Just so you are aware, if your File has more lines than 140 you will get an `ArrayIndexOutOfBoundsException`. Likewise, if you file is less than 140 lines, you may return a null value (which may not be what you want). – Zachary Jan 06 '18 at 04:49

1 Answers1

1

The statement

i= i++;

ends up not incrementing the value of i, so all the lines read from the file end up being written to phrases[0], i.e. only the last line is stored at phrases[0]. That line should be

i++;

or

i=i+1;

To explain, for i=i++; the following happens:

  1. The current value of i (the initial value, 0) is saved temporarily
  2. i is incremented
  3. The temporarily saved value of i is assigned back to i

Thus i never gets incremented. This comes from the definition of the post-increment operator, i.e. the trailing ++

Jim Garrison
  • 85,615
  • 20
  • 155
  • 190