Ways to get user input in Java

Source: Internet
Author: User

1. Using the Java.util.Scanner class

Using the Scannerd Next () method, the test code reads as follows:

    1. Scanner sc=New Scanner (system.in);
    2. System.out.println ("Waiting Inputchar:");
    3. String N=sc.next ();
    4. SYSTEM.OUT.PRINTLN (n);

Of course remember to introduce the relevant package:

    1. Import Java.util.Scanner;

2. Using the BufferedReader class to obtain user input

BufferedReader class is a subclass of Java.IO.Reader

The instance code is as follows:

  1. Using BufferedReader to get user input
  2. BufferedReader receives an instance of the Java.io.reader class
  3. Here we can use Java. Io. InputStreamReader
  4. When using flow operation, remember to add exception handling, or you will report an error
  5. Try
  6. {
  7. BufferedReader bt=New BufferedReader (new InputStreamReader (system.in));
  8. String S=bt.readline ();
  9. System.out.println (s);
  10. }
  11. catch (Java.io.IOException ex)
  12. {
  13. System.out.println (Ex.getmessage ());
  14. }

Here to add a try. catch () exception handling block, or the following exception is reported:

    1. Exception in thread "main" java.lang.Error:Unresolved compilation problem:
    2. Unhandled Exception type IOException

Ways to get user input in Java

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.