简体   繁体   中英

How can I read only one thing in from a textfile?

I can read in from the file and am able to change the amount of lines given by changing the number in the for loop but I don't want all the numbers in my file displayed side by side like that. I need them all going down one by one randomly.

public class Assignment2 {

    public static void main(String[] args) throws IOException 
    {
        // Read in the file into a list of strings
        BufferedReader reader = new BufferedReader(new FileReader("textfile.txt"));
        List<String> lines = new ArrayList<String>();

        String line = reader.readLine();

        while( line != null ) {
            lines.add(line);
            line = reader.readLine();
        }

        // Choose a random one from the list
        Random r = new Random();

        for (int p = 0; p<3; p++)
        {
            String randomString = lines.get(r.nextInt(2));
            System.out.println(lines);
        }
    }
}

I think what you want to print is

String randomString = lines.get(r.nextInt(2));
System.out.println(randomString);

To display only the first 20 random lines from this list of maybe 100

for (int i = 0; i < 20; i++) {

   int rowNum = r.nextInt(lines.size ());
   System.out.println(lines.get(rowNum);
}

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