Android(java)学习笔记36:Scanner类使用

1. Scanner类使用

 1 package cn.itcast_01;
 2 
 3 /*
 4  * Scanner:用于接收键盘录入数据。
 5  * 
 6  * 前面的时候:
 7  *         A:导包
 8  *         B:创建对象
 9  *         C:调用方法
10  * 
11  * System类下有一个静态的字段:
12  *         public static final InputStream in; 标准的输入流,对应着键盘录入。
13  * 
14  *         InputStream is = System.in;
15  * 
16  * class Demo {
17  *         public static final int x = 10;
18  *         public static final Student s = new Student();
19  * }
20  * int y = Demo.x;
21  * Student s = Demo.s;
22  * 
23  * 
24  * 构造方法:
25  *         Scanner(InputStream source)
26  */
27 import java.util.Scanner;
28 
29 public class ScannerDemo {
30     public static void main(String[] args) {
31         // 创建对象
32         Scanner sc = new Scanner(System.in);
33 
34         int x = sc.nextInt();
35         
36         System.out.println("x:" + x);
37     }
38 }


测试类: 

 1 package cn.itcast_02;
 2 
 3 import java.util.Scanner;
 4 
 5 /*
 6  * 基本格式:
 7  *         public boolean hasNextXxx():判断是否是某种类型的元素
 8  *         public Xxx nextXxx():获取该元素
 9  * 
10  * 举例:用int类型的方法举例
11  *         public boolean hasNextInt()
12  *         public int nextInt()
13  * 
14  * 注意:
15  *         InputMismatchException:输入的和你想要的不匹配
16  */
17 public class ScannerDemo {
18     public static void main(String[] args) {
19         // 创建对象
20         Scanner sc = new Scanner(System.in);
21 
22         // 获取数据
23         if (sc.hasNextInt()) {
24             int x = sc.nextInt();
25             System.out.println("x:" + x);
26         } else {
27             System.out.println("你输入的数据有误");
28         }
29     }
30 }

 

posted on 2015-06-02 21:12  鸿钧老祖  阅读(614)  评论(0编辑  收藏  举报

导航