Home > Java > javaTutorial > Introduction to the usage of Scanner class in Java

Introduction to the usage of Scanner class in Java

零下一度
Release: 2017-07-21 15:43:53
Original
2580 people have browsed it

Java 5 adds the java.util.Scanner class, a new utility for scanning input text. It is some combination between the previous StringTokenizer and Matcher classes. Since any data must be retrieved through capturing groups of the same schema or by using an index to retrieve individual parts of the text. You can then use regular expressions in conjunction with methods for retrieving specific types of data items from the input stream. In this way, in addition to using regular expressions, the Scanner class can also arbitrarily analyze data of strings and basic types (such as int and double). With Scanner, you can write a custom parser for any text content you want to process.

Requirement: Enter a month with the keyboard and output the season corresponding to the month.

There are four seasons in a year

3,4,5 Spring

6,7,8 Summer

9,10,11 Autumn

12,1,2 Winter

Analysis:

A: Enter a month with the keyboard and use Scanner to implement

B: Determine which month the month is and output according to the month Corresponding season

public class Test2 {
public static void main(String[] args) {// 键盘录入一个月份,用Scanner实现Scanner sc = new Scanner(System.in);
// 接收数据System.out.println("请输入月份(1-12):");
int month = sc.nextInt();switch(month) {
case 1:case 2:case 12:
            System.out.println("冬季");break;case 3:case 4:case 5:
            System.out.println("春季");break;case 6:case 7:case 8:
            System.out.println("夏季");break;case 9:case 10:case 11:
            System.out.println("秋季");break;default:
                System.out.println("你输入的月份有误");break;
        }
    }
}
Copy after login

Of course there are many other methods, but only one is demonstrated here

The above is the detailed content of Introduction to the usage of 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