Home >Java >javaTutorial >Introduction to the usage of Scanner class in Java
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; } } }
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!