Reputation:
Hi, I'm a newbie to java. I need to code a program where a genie tells someone their fortune. For this program, I take in input from a program based on a random number (from math.random) and return the line of text from whichever number (1-100) they returned. Can someone help me approach this problem (preferably without the use of professional classes I do not understand). Thank you!
public void askFortune()
{
Scanner input = new Scanner("fortunes.txt");
double number = Math.random();
int num = (int) number * 100;
num += 1;
}
Upvotes: 0
Views: 134
Reputation: 2551
It's traditional way of java's IO.
public void askFortune() {
BufferedReader input = null;
double number = Math.random();
int num = (int) (number * 100);
num += 1;
int lineCount = 0;
String line = "";
try {
String foundLine = null;
input = new BufferedReader(
new InputStreamReader(new FileInputStream("fortunes.txt")));
while((line = input.readLine()) != null)
{
if(num == lineCount)
{
foundLine = line;
break;
}
lineCount++;
}
if(foundLine != null)
System.out.printf("Found line[%d]:%s\n", num, foundLine);
else
System.out.println("Wrong line number" + number + ":" + num);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
You have to check the following line,
int num = (int) number * 100;
It might cause an operand order problem, if you are expected 1 to 100 as a range of the line number then change it with.
You can either use
int num = (int) (number * 100);
or
int num = (int) (Math.random() * 100) + 1;
instead of
double number = Math.random();
int num = (int) (number * 100);
num += 1;
I hope it helps...
Upvotes: 0
Reputation: 521168
You may try iterating your scanner until either you reach the random line, or the end of the scanner is reached:
public void askFortune() {
Scanner input = new Scanner("fortunes.txt");
double number = Math.random();
int num = (int) number * 100;
num += 1;
int counter = 0;
String line = "";
while (counter < number) {
if (!input.hasNextLine()) {
break;
}
line = input.nextLine();
++counter;
}
if (counter == number) {
System.out.println("Found line:\n" + line);
}
else {
System.out.println("Input file does not have enough lines");
}
}
Upvotes: 2