Home > Java > javaTutorial > How to use the Scanner class in java

How to use the Scanner class in java

王林
Release: 2020-04-28 11:51:22
Original
6253 people have browsed it

How to use the Scanner class in java

Scanner class introduction

java.util.Scanner is a new feature of Java5. User input can be obtained through the Scanner class.

Basic syntax for creating a Scanner object:

Scanner s = new Scanner(System.in);
Copy after login

(Video tutorial recommendation: java video)

Example:

Next We demonstrate the simplest data input and obtain the input string through the next() and nextLine() methods of the Scanner class. Before reading, we generally need to use hasNext and hasNextLine to determine whether there is still input data:

import java.util.Scanner; 
 
public class ScannerDemo {
    public static void main(String[] args) {
        Scanner scan = new Scanner(System.in);        // 从键盘接收数据
 
        // next方式接收字符串
        System.out.println("next方式接收:");        // 判断是否还有输入
        if (scan.hasNext()) {
            String str1 = scan.next();            
            System.out.println("输入的数据为:" + str1);
        }
        scan.close();
}}
Copy after login

The results are as follows:

$ javac ScannerDemo.java
$ java ScannerDemo
next方式接收:
php cn
输入的数据为:php
Copy after login

Recommended tutorial:java entry program

The above is the detailed content of How to use the Scanner class in java. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template