Java Basics Enhanced IO flow notes 47:io stream exercise random get name case in text file

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.