I need to write a program that gets inputted files from arguments written from command prompt and prints a random line from it. I don't really know how many exceptions i need and I don't really understand the logic of getting the line from the file. Please help me.

Dani AI

Generated

Two practical ways to solve this for depending on file size and simplicity. 's pointer to input helpers is useful, and 's suggestion to handle exceptions is fine as a start — but prefer handling the specific exceptions you expect instead of a blanket catch-all so you can report useful errors (missing arg, unreadable file, empty file).

If the file is small or you don't care about memory, read all lines into a List and pick a random index. This is simplest and very readable. For large files, use one-pass reservoir sampling so you never store more than one line in memory and still get a uniformly random line.

Example — simple (reads whole file):

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

List<String> lines = Files.readAllLines(Paths.get(args[0]));
if (lines.isEmpty()) { System.err.println("empty"); return; }
System.out.println(lines.get(new Random().nextInt(lines.size())));

Example — single-pass (reservoir sampling, memory constant):

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

String chosen = null;
Random rnd = new Random();
int count = 0;
try (BufferedReader br = new BufferedReader(new FileReader(args[0]))) {
    String line;
    while ((line = br.readLine()) != null) {
        count++;
        if (rnd.nextInt(count) == 0) chosen = line;
    }
} catch (IOException e) {
    e.printStackTrace();
}
if (chosen == null) System.err.println("no lines");
else System.out.println(chosen);

Troubleshooting notes: check args.length first; handle IOException (and SecurityException if running with restricted IO). If you expect multiple filenames, either iterate them and print one random line per file or combine their lines into the same reservoir pass. When testing, use small predictable files and a fixed Random seed to verify uniformity.

Recommended Answers

All 2 Replies

I don't really know how many exceptions i need

if you want to have a minimum, just put everything in one HUUUGE try-catch block, catching a standard Exception.

otherwise, just write the code you think you'll need, try to compile it and you should get messages like:

unhandled ...Exception at line ...

that should give you an idea of what Exception to handle with, and, more important, about where to do so

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.