简体   繁体   中英

How do you print a specific line of text from a text file using math.random in Java?

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

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

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...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM