First, we should introduce the package import Java.util.Scanner;
It is a simple text scanner that can use regular expressions to parse basic types and strings. Scanner uses the separator mode to decompose its input into tokens, which, by default, match the delimiter pattern. You can then use a different next method to convert the resulting token to a different type of value.
Scanner reader=new Scanner (system.in);
The reader object then invokes the following methods (functions) to read the various data types entered by the user at the command line
Next. Byte (), nextdouble (), Nextfloat,nextint (), nextline (), Nextlong (), Nextshot ()
The above method will cause congestion when it is executed, waiting for the user to enter data entry confirmation at the command line. For example, advocating in keyboard input
The value of 12.34,hasnextfloat () is true, and the value of Hasnextint () is false. Nextline () waits for the user to enter a text
Line and enter, the method gets a string of data.
For example, the following code enables a user to read a number from system.in:
Scanner sc = new Scanner (system.in);
int i = Sc.nextint ();
Again for example:
Import Java.util.Scanner;
public class Example
{public
static void Main (String args[])
{
System.out.println ("Please enter a number of Each input a number with carriage return confirmation ");
System.out.println ("Enter a non-digit end input operation");
Scanner reader=new Scanner (system.in);
Double sum=0;
int m=0;
while (Reader.hasnextdouble ())
{
double x=reader.nextdouble ();
m=m+1;
sum=sum+x;
}
System.out.printf ("Number of%d and%f\n", m,sum);
System.out.printf ("The average number of%d is%f\n", m,sum/m);
}
Common methods
Another example:
Scan files line by row and output line by row
Scanner cin=new Scanner (system.in);
while (Cin.hasnext ()) {
System.out.println (Cin.next ());
}
When a Scanner is created via new Scanner (system.in), the console waits for input until the ENTER key is finished, passing the input to Scanner as the scanned object. If you want to get the input, you only need to call the scanner Nextline () method.
/** * Scan Console input * * @author leizhimin 2009-7-24 the 11:24:47/public class Testscanner {
public static void Main (string[] args) {Scanner s = new Scanner (system.in);
System.out.println ("Please enter a string:");
while (true) {String line = S.nextline ();
if (Line.equals ("Exit")) break;
System.out.println (">>>" + line); }
}
}