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

Dani AI

Generated

asked for a way to pick random names by number; was on the right track suggesting a collection. Two simple, practical options follow: pick by random index (allows repeats) or pick without repeats by shuffling/taking a slice. Use a list where each element is a line from the file — the element index is the line number (index 0 = first line, add 1 for human-friendly numbering).

Java (reads whole file, then shuffle or pick an index):

import java.nio.file.*;
import java.util.*;

List<String> names = Files.readAllLines(Paths.get("names.txt"));
names.removeIf(String::isBlank);                // skip empty lines
Collections.shuffle(names);                     // for unique picks
for (int i = 0; i < Math.min(requested, names.size()); i++)
    System.out.println(names.get(i));

Or pick with replacement (may repeat):

Random rng = new Random();
int idx = rng.nextInt(names.size());            // 0..size-1
System.out.println(names.get(idx));

Python (concise and readable):

import random
with open('names.txt') as f:
    names = [l.strip() for l in f if l.strip()]
print('\n'.join(random.sample(names, k=min(requested, len(names)))))  # unique
# or use random.choice(names) repeatedly for replacement

Notes and cautions: trim whitespace and skip blank lines so indexes line up with visible names. If the file is huge (millions of lines), avoid readAllLines/read into memory — use streaming or reservoir sampling to pick k items in one pass with O(k) memory. Decide whether repeats are allowed; if not, shuffle or sample without replacement. For reproducible output use a fixed seed in Random/random.seed(). Validate the user’s requested count (don't request more unique names than exist unless repeats are allowed).

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.