gpt4 book ai didi

java - 如何在 Java 中使用 math.random 从文本文件打印特定文本行?

转载 作者:塔克拉玛干 更新时间:2023-11-03 05:51:19 24 4
gpt4 key购买 nike

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;
}

最佳答案

您可以尝试迭代扫描器,直到到达随机行或到达扫描器的末尾:

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");
}
}

关于java - 如何在 Java 中使用 math.random 从文本文件打印特定文本行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50284663/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com