|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
1、简介
在JDK5以后出现的用于键盘录入数据的类;需要导包 java.util.Scanner 。
语法:
Scanner s = new Scanner(System.in);
System.in 是标准的输入流,对应于键盘录入。
构造方法(之一):
Scanner(InputStream source, String charsetName)
构造一个新的 Scanner,它生成的值是从指定的输入流扫描的。
2、用法
基本方法格式:
A: hasNextXxx() 判断是否是某种类型的。
B: nextXxx() 返回某种类型的元素。
通过 Scanner 类的 next() 与 nextLine() 方法获取输入的字符串,在读取前我们一般需要 使用 hasNext 与 hasNextLine 判断是否还有输入的数据。
next方式:
- 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();
- }
- }
复制代码 nextLine方式:
- import java.util.Scanner;
-
- public class ScannerDemo {
- public static void main(String[] args) {
- Scanner scan = new Scanner(System.in);
- // 从键盘接收数据
-
- // nextLine方式接收字符串
- System.out.println("nextLine方式接收:");
- // 判断是否还有输入
- if (scan.hasNextLine()) {
- String str2 = scan.nextLine();
- System.out.println("输入的数据为:" + str2);
- }
- scan.close();
- }
- }
复制代码 next() 与 nextLine() 区别:
next():
① 一定要读取到有效字符后才可以结束输入。
② 对输入有效字符之前遇到的空白,next() 方法会自动将其去掉。
③ 只有输入有效字符后才将其后面输入的空白作为分隔符或者结束符。
④ next() 不能得到带有空格的字符串。
nextLine():
① 以Enter为结束符,也就是说 nextLine()方法返回的是输入回车之前的所有字符。
② 可以获得空白。
输入 int 或 float 类型的数据,在 Scanner 类中也有支持,但是在输入之前最好先使用 hasNextXxx() 方法进行验证,再使用 nextXxx() 来读取:
- import java.util.Scanner;
-
- public class ScannerDemo {
- public static void main(String[] args) {
- Scanner scan = new Scanner(System.in);
- // 从键盘接收数据
- int i = 0;
- float f = 0.0f;
- System.out.print("输入整数:");
- if (scan.hasNextInt()) {
- // 判断输入的是否是整数
- i = scan.nextInt();
- // 接收整数
- System.out.println("整数数据:" + i);
- } else {
- // 输入错误的信息
- System.out.println("输入的不是整数!");
- }
- System.out.print("输入小数:");
- if (scan.hasNextFloat()) {
- // 判断输入的是否是小数
- f = scan.nextFloat();
- // 接收小数
- System.out.println("小数数据:" + f);
- } else {
- // 输入错误的信息
- System.out.println("输入的不是小数!");
- }
- scan.close();
- }
- }
复制代码 |
|