Several common ways to enter data from the console in Java

Source: Internet
Author: User


Several common ways to enter data from the console in Java

First, using the standard input string system.in
System.in.read () reads only one byte of data at a time, and we usually get a string or a set of numbers
System.in.read () returns an integer
Must initialize
int read = 0;
char read = ' 0 ';
SYSTEM.OUT.PRINTLN ("Input data:");
try {
Read = System.in.read ();
Read = (char) System.in.read ();
}catch (Exception e) {
E.printstacktrace ();
}
SYSTEM.OUT.PRINTLN ("Input data:" +read);

Second, use scanner to get a string or a set of numbers
System.out.print ("input");
Scanner scan = new Scanner (system.in);
String read = Scan.nextline ();
SYSTEM.OUT.PRINTLN ("Input data:" +read);

/* A System.in object is required when adding a new scanner object because the system.in is actually getting user input. The next () method of the scanner is used to obtain the user input string, nextint () converts the obtained input string to an integer type, and similarly, nextfloat () is converted to a floating-point type; Nextboolean () is converted to a Boolean type. */

Iii. using BufferedReader to obtain input with spaces

Scanner obtained input with space, tab, enter key as Terminator,
To get input containing space, you can use the Java.io.BufferedReader class to implement
Using the BufferedReader ReadLine () method
Java.io.IOException exception must be handled
BufferedReader br = new BufferedReader (new InputStreamReader (system.in));
Java.io.InputStreamReader inherits the reader class
String read = null;
System.out.print ("Input data:");
try {
Read = Br.readline ();
} catch (IOException e) {
E.printstacktrace ();
}
SYSTEM.OUT.PRINTLN ("Input data:" +read);

Several common ways to enter data from the console 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.