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

时间:2023-03-08 22:47:58

1. Scanner类使用

 package cn.itcast_01;

 /*
* Scanner:用于接收键盘录入数据。
*
* 前面的时候:
* A:导包
* B:创建对象
* C:调用方法
*
* System类下有一个静态的字段:
* public static final InputStream in; 标准的输入流,对应着键盘录入。
*
* InputStream is = System.in;
*
* class Demo {
* public static final int x = 10;
* public static final Student s = new Student();
* }
* int y = Demo.x;
* Student s = Demo.s;
*
*
* 构造方法:
* Scanner(InputStream source)
*/
import java.util.Scanner; public class ScannerDemo {
public static void main(String[] args) {
// 创建对象
Scanner sc = new Scanner(System.in); int x = sc.nextInt(); System.out.println("x:" + x);
}
}

测试类: 

 package cn.itcast_02;

 import java.util.Scanner;

 /*
* 基本格式:
* public boolean hasNextXxx():判断是否是某种类型的元素
* public Xxx nextXxx():获取该元素
*
* 举例:用int类型的方法举例
* public boolean hasNextInt()
* public int nextInt()
*
* 注意:
* InputMismatchException:输入的和你想要的不匹配
*/
public class ScannerDemo {
public static void main(String[] args) {
// 创建对象
Scanner sc = new Scanner(System.in); // 获取数据
if (sc.hasNextInt()) {
int x = sc.nextInt();
System.out.println("x:" + x);
} else {
System.out.println("你输入的数据有误");
}
}
}