Java Scanner Class

Source: Internet
Author: User
Tags java se

Java.util.Scanner is a new feature of JAVA5, and we can get the user's input through the Scanner class.
Here is the basic syntax for creating a Scanner object:
Scanner s = new Scanner (system.in);
Next we demonstrate the simplest data input, and get the input string through the next () and Nextline () method of the Scanner class, before reading we generally need to use Hasnext and hasnextline to determine if there is any data to be entered:
Use the Next method:
Scannerdemo.java File Code:
Import Java.util.Scanner;

public class Scannerdemo {
public static void Main (string[] args) {
Scanner scan = new Scanner (system.in);
receiving data from the keyboard

    // next方式接收字符串    System.out.println("next方式接收:");    // 判断是否还有输入    if (scan.hasNext()) {        String str1 = scan.next();        System.out.println("输入的数据为:" + str1);    }    scan.close();}

}
Execute the above program output as:
$ Javac Scannerdemo.java
$ Java Scannerdemo
Next way to receive:
Runoob com
The data entered is: Runoob
You can see the COM string is not output, next we look at nextline.
Use the Nextline method:
Scannerdemo.java File Code:
Import Java.util.Scanner;

public class Scannerdemo {
public static void Main (string[] args) {
Scanner scan = new Scanner (system.in);
receiving data from the keyboard

    // nextLine方式接收字符串    System.out.println("nextLine方式接收:");    // 判断是否还有输入    if (scan.hasNextLine()) {        String str2 = scan.nextLine();        System.out.println("输入的数据为:" + str2);    }    scan.close();}

}
Executes the above program output as:
$ javac Scannerdemo.java
$ java scannerdemo
nextline mode receive:
Runoob com
The data entered is: Runoob com
can see the COM string output.
Next () differs from nextline ()
Next ():
1, be sure to read the valid characters before you can end the input.
2, the next () method automatically removes the whitespace that is encountered before entering a valid character.
3, only enter a valid character after the white space after it as a delimiter or terminator.
Next () cannot get a string with spaces.
Nextline ():
1, with enter as the Terminator, which means that the nextline () method returns all characters before the input carriage return.
2, you can get blank.
If you want to enter data of type int or float, it is also supported in the Scanner class, but it is best to use the Hasnextxxx () method for validation prior to input, and then use NEXTXXX () to read:
Scannerdemo.java file code :
Import Java.util.Scanner;

public class Scannerdemo {
public static void Main (string[] args) {
Scanner scan = new Scanner (system.in);
receiving data from the keyboard
int i = 0;
float F = 0.0f;
System.out.print ("Input integer:");
if (Scan.hasnextint ()) {
Determines whether the input is an integer
i = Scan.nextint ();
Receive integers
System.out.println ("Integer data:" + i);
} else {
Enter the wrong information
SYSTEM.OUT.PRINTLN ("Input is not an integer! ");
}
System.out.print ("Enter decimal:");
if (Scan.hasnextfloat ()) {
Determine if the input is a decimal
f = scan.nextfloat ();
Receive decimals
SYSTEM.OUT.PRINTLN ("Decimal data:" + f);
} else {
Enter the wrong information
SYSTEM.OUT.PRINTLN ("The input is not a decimal!") ");
}
Scan.close ();
}
}
Execute the above program output as:
$ Javac Scannerdemo.java
$ Java Scannerdemo
Input integer: 12
Integer data: 12
Enter decimal: 1.2
Fractional Data: 1.2
The following examples of Beijing stock distribution We can enter multiple numbers, and the sum and average, each input a number with a return confirmation, by entering a non-numeric to end the input and output the execution result:
Scannerdemo.java File Code:
Import Java.util.Scanner;

Class Scannerdemo {
public static void Main (string[] args) {
Scanner scan = new Scanner (system.in);

  Double sum = 0;    int m = 0;        while (Scan.hasnextdouble ()) {Double x = scan.nextdouble ();        m = m + 1;    sum = sum + x;    } System.out.println (M + "sum of" + sums);    System.out.println (the average of the number of M + "is" + (sum/m)); Scan.close ();}  

}
Executes the above program output as:
$ javac Scannerdemo.java
$ java scannerdemo
[
] [
]
21.4
End
The 4-digit and 71.4
4-digit average is 17.85
For more information, refer to the API documentation: HTTP://WWW.RUNOOB.COM/MANUAL/JDK1.6/.
Java Stream (stream), file, and IO Java exception handling br/> note list
Mrodot
mro*** @qq. The characters are visible when the COM
Console cons = System.Console ();
String username = cons.readline ("User name:");
char[] passwd = Cons.readpassword ("Password:");br/> for security reasons, the returned password is stored in a one-dimensional character array instead of in a string. Once the password has been processed, it should be melted Kim with a padding value to overwrite the array element.
Handling input With the console object is less convenient than using scanner. Only one line of input can be read at a time, and there is no way to read a word or a numeric value.
Mrodot
Mrodot
mro*** @qq. COM
seeker98
115***[email protected]
through the StringTokenizer class you can break down a string with spaces for the entire line of input. By default, StringTokenizer is divided by spaces, tabs, newline characters, and carriage returns.
Import Java.util.Scanner;
Import Java.bjrongjinhuiyin.comutil.StringTokenizer;

Class Main {
public static void Main (string[] args) {
Scanner scanner=new Scanner (system.in);
SYSTEM.OUT.PRINTLN ("Input data:");
StringTokenizer stringtokenizer=new StringTokenizer (Scanner.nextline ());
System.out.println ("After Separation:");
while (Stringtokenizer.hasmoretokens ()) {
System.out.println (Stringtokenizer.nexttoken ());
}
}
}
Test results:
$ Javac Main.java
$ Java Main
Input data:
Runoob com
After separation:
Runoob
Com

Java Scanner Class

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.