1. Randomly get name cases in a text file
Requirements: I have a text file stored in a few names, please write a program implementation randomly get a person's name.
Analysis:
A: Storing the data in a text file in a collection
B: Randomly produce an index
C: Gets a value based on the index
2. Code implementation:
1 Packagecn.itcast_02;2 3 ImportJava.io.BufferedReader;4 ImportJava.io.FileReader;5 Importjava.io.IOException;6 Importjava.util.ArrayList;7 ImportJava.util.Random;8 9 /*Ten * Requirements: I have a text file stored in a few names, please write a program implementation randomly get a person's name. One * A * Analysis: - * A: Storing the data in a text file in a collection - * B: Randomly generate an index the * C: Gets a value based on the index - */ - Public classGetName { - Public Static voidMain (string[] args)throwsIOException { + //storing data in a text file in a collection -BufferedReader br =NewBufferedReader (NewFileReader ("B.txt")); +arraylist<string> array =NewArraylist<string>(); AString line =NULL; at while(line = Br.readline ())! =NULL) { - Array.add (line); - } - br.close (); - - //randomly produce an index inRandom r =NewRandom (); - intindex =R.nextint (Array.size ());// 0 <= index <= array.size ()-1 to + //gets a value based on the index -String name =Array.get (index); theSystem.out.println ("The Lucky person is:" +name); * } $}
The operating effect is:
Java Basics Enhanced IO flow notes 47:io stream exercise random get name case in text file