Java中的Scanner类(附带实例)
java.util.Scanner 可以通过 Scanner 类获取用户的输入,本节重点讲解相关方法的用法。
创建 Scanner 对象的基本语法如下:
接下来演示一个最简单的数据输入,并通过 next() 与 nextLine() 方法获取输入的字符串,在读取前通常需要使用 hasNext() 与 hasNextLine() 判断是否还有输入的数据。
接下来我们看 nextLine() 方法:
next() 和 nextLine() 的区别如下:
1) next():
2) nextLine():
【实例】使用 Scanner 类的 nextXxx() 方法接收其他类型数据:
创建 Scanner 对象的基本语法如下:
Scanner s = new Scanner(System.in);
Java字符串的输入
Scanner 类中的 next() 与 nextLine() 方法可以用来接收字符串。接下来演示一个最简单的数据输入,并通过 next() 与 nextLine() 方法获取输入的字符串,在读取前通常需要使用 hasNext() 与 hasNextLine() 判断是否还有输入的数据。
import java.util.*;
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();
}
}
程序执行结果为:
next 方式接收:
hello world
输入的数据为:hello
接下来我们看 nextLine() 方法:
import java.util.Scanner;
public class ScannerDemo1 {
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();
}
}
程序执行结果为:
nextLine 方式接收:
hello world
输入的数据为:hello world
next() 和 nextLine() 的区别如下:
1) next():
- 一定要读取有效字符后才可以结束输入;
- 对输入有效字符之前遇到的空白,next() 方法会自动将其去掉;
- 只有输入有效字符后才将其后面输入的空白作为分隔符或者结束符;
- next() 不能得到带有空格的字符串。
2) nextLine():
- 以 Enter 键为结束符,即 nextLine() 方法返回的是 Enter 键之前的所有字符;
- 可以获得空格字符。
Java其他类型数据的输入
如果要输入 int 或 float 等类型的数据,调用相应的 nextXxx() 即可。但是在输入之前最好先使用 hasNextXxx() 方法进行验证,再使用 nextXxx() 读取。【实例】使用 Scanner 类的 nextXxx() 方法接收其他类型数据:
import java.util.Scanner;
public class ScannerDemo3 {
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();
}
}
程序执行结果为:
输入整数:20
整数数据:20
输入小数:3.5
小数数据:3.5
ICP备案:
公安联网备案: