-3

So I need to do exactly what it says in the title, take a text file called "words.txt", have the program read it, take all the words in it, and store them into an array. After that, the program needs to pick one out randomly, and print it in reverse. I'm having a lot of trouble getting it to work, as it always crashes at the end. Here's what I got so far:

import java.io.*;
import java.util.Random;

public class wordReader{
   public static void main (String args[]) throws Exception{
      BufferedReader br = new BufferedReader(new FileReader("words.txt"));
      String strLine;
      String[] filearray;
      filearray = new String[10];

      while ((strLine = br.hasNextLine())) {
         for (int j = 0; j < filearray.length; j++){
            filearray[j] = br.readLine();
            System.out.println(filearray);
         }
      }
   }
}

Alright, this i what I have at the moment:

import java.io.*;
import java.util.Random;

public class wordReader{
   public static void main (String args[]) throws Exception{
      BufferedReader br = new BufferedReader(new FileReader("words.txt"));
      String strLine;
      String[] filearray;
      filearray = new String[10];
      int j = 0;
      int i = 0;
      Random r = new Random();  
      while(((strLine = br.readLine()) !=null) && j < filearray.length){
         filearray[j++] = strLine;
         int idx = r.nextInt(filearray.length);
      }
   }
}
JasonBreen
  • 31
  • 1
  • 2
  • 9

4 Answers4

2

You can do this easily using the new Files API and StringBuilder to reverse your String. It will cut down your lines of code significantly.

public static void main(String[] args) throws Exception {  
    Path path = Paths.get("words.txt");
    Charset charset = StandardCharsets.UTF_8;

    String content = new String(Files.readAllBytes(path), charset);
    String[] words = content.split(",|\.|\s+");

    int randomIndex = new Random().nextInt(words.length);
    String word = words[randomIndex];

    String reversed = StringBuilder(word).reverse().toString();
    System.out.println(reversed);
}
ktm5124
  • 11,861
  • 21
  • 74
  • 119
0

Try using the StringTokenizer to read the line.

http://docs.oracle.com/javase/7/docs/api/java/util/StringTokenizer.html

 StringTokenizer st = new StringTokenizer("this is a test");
     while (st.hasMoreTokens()) {
         System.out.println(st.nextToken());
     }
Chris Hinshaw
  • 6,967
  • 2
  • 39
  • 65
0

You don't seem to have gotten to the point of doing the random index selection or the line reversal yet, so I won't address that stuff here. There are endless duplicates all over StackOverflow to tell you how to reverse a String.

At the moment, you're getting compile errors because (among other things) you're trying to use a method (BufferedReader#hasNextLine()) that doesn't exist. It looks like you were mixing up a couple of other approaches that you might have found, e.g.:

int j = 0;
while ((strLine = br.readLine()) != null) { // Set strLine to the next line
    filearray[j++] = strLine; // Add strLine to the array
    // I don't recommend printing the whole array on every pass through the loop...
}

You'll notice that I also took out your inner for loop, because it was just setting every element of your list to the most recent line on every iteration. I'm assuming you wanted to populate the list with all of your lines. Realistically, you should also check whether j is in an acceptable range as well:

while (((strLine = br.readLine()) != null) && j < filearray.length) {...}

Note that realistically, you'd almost certainly be better off using a List to store your lines, so you could just add all the lines to the List and not worry about the length:

List<String> contents = new ArrayList<String>();
while ((strLine = br.readLine()) != null) {
    contents.add(strLine); // Add strLine to the List
}

But, this does smell like homework, so maybe you're required to use a String[] for whatever reason.


Finally, there's a discrepancy between what you've written in your question and what your program looks like it's intended to do. You claim that you need a list of each word, but it looks more like you're trying to create a list of each line. If you need words instead of lines, you'll need to split up each line and add each token to the list.

Henry Keiter
  • 16,863
  • 7
  • 51
  • 80
  • So, how would I slect randomly, and print in reverse? I need a for loop for reverse, dont I? – JasonBreen Mar 04 '14 at 18:23
  • Nah, dont NEED to use a String[], I just want to get it to work. – JasonBreen Mar 04 '14 at 18:30
  • @Jason There are lots of ways to do line reversal and random selection. Once you've built your list of lines, [choose a random index](http://docs.oracle.com/javase/7/docs/api/java/util/Random.html) in your array, and then [loop backwards through that String](http://stackoverflow.com/q/2713655/2069350). – Henry Keiter Mar 04 '14 at 18:31
0

Lot's of ways to accomplish this. Here's a recursive method that prints as the calls are popping off the return stack. This was adapted from Reversing Lines With Recursion Java

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.PrintWriter;

public class ReverseLines {

    public static BufferedReader input;
    public static PrintWriter output;

    public static void main(String[] args) throws Exception {

        input = new BufferedReader(new FileReader("/tmp/words.txt"));
        output = new PrintWriter(System.out);
        reverse(input, output);
        input.close();
        output.flush();
        output.close();

    }

    public static void reverse(BufferedReader input, PrintWriter output)
            throws Exception {

        String line = input.readLine();
        if (line != null) {
            reverse(input, output);
            output.println(line);
        }
    }

}
Community
  • 1
  • 1
David H. Bennett
  • 1,822
  • 13
  • 16