2

This is a little hard to explain, but here goes nothing. I am creating a program that creates excuses for example:

"I am sorry, but my dog ate my homework!"

The way I'll make it random is by placing the intros "I am sorry but" in a text file on it's own line, and then do the same to the culprits "my dog", and the reasons "ate my homework!". I would like to know how to make a variable equal to the line of one of the files. I did this for another program, this one created random Shakespearean insults, but I did it in python. The way I did it was:

adjective = random.choice(open('/filepath*', 'r').readlines()).strip()

I would like to do the same but in Java, but I am at a loss as to how. Any suggestions? ( I would prefer something that can be done in a single line like in python)

Thakns for the help.

lokilindo
  • 682
  • 5
  • 17
  • The Python example splits words, not lines. – 5gon12eder Oct 25 '15 at 04:38
  • @5gon12eder You are technically correct (the best kind of correct) in my python program I use only words but even if I had used phrases it would be similar,something along the lines of: `adjective = random.choice(open('/filepath*', 'r').readlines()).strip()` would work too I believe :) – lokilindo Oct 25 '15 at 06:21
  • Fair enough. I was asking because the distinction between words and lines might be important for the answer you are looking for, even if it didn't make any difference for the actual input file you once had. Maybe you want to edit your question to use the `readlines` snippet? – 5gon12eder Oct 25 '15 at 06:33

3 Answers3

1

You could try using the Files class from java.nio.file.Files to read the file, then randomly choose the index to grab within the resulting list of lines. Something like this:

    List<String> lines = Files.readAllLines(Paths.get("/filepath"));
    String adjective = lines.get(new Random().nextInt(lines.size()));
Nate Jenson
  • 2,664
  • 1
  • 25
  • 34
0

Ouch! That would hurt java devs. Unlike python, you need a lot of codes to do simple tasks in java, mainly because it's a compile first then interpret language.

Coming to your issue, I'm not a design expert, but this outline could help, keep your excuse, culprit, and reason in three different text files.

"Stream line" those files to bufferedreaders.

Use math.random(totLinesInParticularFile) and read till the result of it using the bufferedreader.

Combine the results from the three reads and voila you've it! Btw there may be a better design.

Cybermonk
  • 514
  • 1
  • 6
  • 28
0

I guess you can use Stream in java to do this job, but it's quite complicated.

Assuming you have files about culprits and reasons, you can read the line of the file into a java program by the BufferedReader, which can read a line at a time, then you can add the line to a prepared String[] array and use the Random class in java to get the random line to make up a scentence and write it out in your outside text.

HiCrispy
  • 1
  • 1
  • 3