Java common class: scanner class


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


Scanner scanner = new Scanner(;

3、 Common methods

I. getting input


  1. next(): get the next input string.
  2. 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.


II. Is there any input


  1. hasNext(): judge whether there is another user input.
  2. hasNextLine(): judge whether there is the next line of user input.



III. turn off reception


  • 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.



4、 Comprehensive examples

public static void main(String[] args) {
    Scanner scanner = new Scanner(;
    double sum = 0.0;
    int num = 0;
    /*The loop ends when a non numeric string is entered*/
    while (scanner.hasNextDouble()) {
        double x = scanner.nextDouble();
        sum = sum + x;
    System.out.println The sum of num + number is + sum;
    System.out.println (Num + "the average number is" + (sum / Num));

Recommended Today

Practice analysis of rust built-in trait: partialeq and EQ

Abstract:Rust uses traits in many places, from simple operator overloading to subtle features like send and sync. This article is shared from Huawei cloud community《Analysis of rust built-in trait: partialeq and EQ》Author: debugzhang Rust uses traits in many places, from simple operator overloading to subtle features like send and sync. Some traits can be automatically […]