Java common class: scanner class

Time:2021-3-4

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:

  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.

Example:

scanner.next();
scanner.nextLine();


II. Is there any input

method:

  1. hasNext(): judge whether there is another user input.
  2. 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();
}


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 […]