Hello so the code i need to write needs to read a text file and print as many random names as a user tells it to. so i have everything but cant figure out how assign a line of the file a number so i can just come up with random numbers and print the line that corresponds to the integer that was inputted from the keyboard.

the file just has names that look like this:
Alex
Phil
Brandon
Sarah
Heather
...

thanks

Recommended Answers

All 3 Replies

Load it into a Vector (or array of Strings) and let the position be the line number.

i dont know vectors...the way im almost positive that im supposed to do it is to make each line of the file an array. how would i do that?

Here is a method of loading an array:
I used a parameter to set the max, but this can be done a multitude of different ways.

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

public class ReadTextFile
{
   public static boolean Load(String strFileName, String[] arr, int iMax, Object strError)
   {
      boolean blnRetVal = true;
      try
      {
         int i = 0;
         String strData = "";
         BufferedReader fileIn = new BufferedReader(new FileReader(strFileName));
         while(null != (strData = fileIn.readLine()) && (i < iMax))
         {
            arr[i++] = strData;
         }
         fileIn.close();
      }
      catch(Exception exc)
      {
         blnRetVal = false;
         strError = exc.getMessage();
      }
      return blnRetVal;
   }
   public static void main(String[] args)
   {
      String[] arr = new String[30];

      String strError = "";

      if(!Load("Text1.txt", arr, 30, strError))
      {
         System.out.println("Could not load input file: " + strError);
         return;
      }

      for(int i=0; (i<arr.length && null != arr[i]); i++)
      {
         System.out.println(i +" "+ arr[i]);
      }
   }
}
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.