1、 Introduction
- java.util.Scanner It’s a new feature of Java 5. We can use the scanner class toGet user input。
2、 Creating objects
Example:
Scanner scanner = new Scanner(System.in);
3、 Common methods
I. getting input
method:
- next(): get the next input string.
- nextLine(): gets the string entered by the user on the next line.
The difference between the two is as follows:
- next:
- You must read a valid character before you can end the input.
- The next method will automatically remove the white space encountered before entering a valid character.
- Only after a valid character is entered, the blank character entered after it will be used as a separator or terminator.
- The next method cannot get a string with a white space character.
- nextLine:
- It ends with a newline character, which means that the nextline method returns all the characters before the newline character is entered.
- You can get white space.
Example:
scanner.next();
scanner.nextLine();
II. Is there any input
method:
- hasNext(): judge whether there is another user input.
- hasNextLine(): judge whether there is the next line of user input.
Example:
scanner.hasNext();
scanner.hasNextLine();
III. turn off reception
method:
- close(): turn off the scanner’s reception of user input.
be careful:
- All classes belonging to IO stream will occupy resources if they are not closed.
Example:
scanner.close();
4、 Comprehensive examples
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
double sum = 0.0;
int num = 0;
/*The loop ends when a non numeric string is entered*/
while (scanner.hasNextDouble()) {
double x = scanner.nextDouble();
num++;
sum = sum + x;
}
System.out.println The sum of num + number is + sum;
System.out.println (Num + "the average number is" + (sum / Num));
scanner.close();
}