Java three ways to read data from the keyboard __java

Source: Internet
Author: User

1. Read a single character:
Reads the next byte of data from the input stream, returns the int byte value within the 0~255 range, and returns 1 if the end of the input stream is reached. So you need to convert the int type to the char type when reading the char type

System.out.println ("Please enter:");
char C = (char) System.in.read ();
System.out.println (c);

2. Read one line:
BufferedReader reads text from the character input stream and buffers individual characters to enable efficient reading of characters, arrays, and rows. You can specify the size of the buffer, but in most cases the default value is sufficient to use the

System.out.println ("Please enter:");
BufferedReader br = new BufferedReader (new InputStreamReader (system.in));
String str = br.readline ();
System.out.println (str);

3. Powerful scanner
Scanner is a simple text scanner that can use regular expressions to parse basic types and strings.
It uses the separator mode (by default, the separator pattern matches white space) to decompose its input into tokens, and then converts the resulting token to a different type of value using a different next method

System.out.println ("Please enter:");
Scanner sc = new Scanner (system.in);

String name = Sc.next ();  Next () reads the value of type string
int age = Sc.nextint ();  Nextint () reads the value of type int.
Double weight = sc.nextdouble ();  Nextdouble () reads a value of type double

System.out.println ("Name: + name +", Age: "+ ages +", Weight: "+ weight);
Related Article

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.