Scanner类:
API介绍:
解析:
Scanner类是一个文本扫描器类,对字符串文本进行扫描操作。
构造方法:
import java.io.File;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.util.Scanner;
public class Demo4 {
public static void main(String[] args) throws FileNotFoundException {//throws FileNotFoundException用来抛出io的错误,
//1,Scanner(File) 扫描文件
File file = new File("C:\\Users\\Administrator\\Desktop\\text1.txt");
Scanner input = new Scanner(file);
//注意:直接输出对象,就是调用该对象的toString()方法
System.out.println(input);
//2,Scanner(InputStream) 扫描键盘
InputStream in = System.in;
Scanner input2 = new Scanner(in);
System.out.println(input2);
//3,Scanner(String) 扫描自定义字符串
String str = "abc";
Scanner input3 = new Scanner(str);
System.out.println(input3);
}
}
常用功能方法:
import java.util.Scanner;
public class Demo4 {
public static void main(String[] args) throws FileNotFoundException {//throws FileNotFoundException用来抛出io的错误,
Scanner input = new Scanner(System.in);
String str1 = input.next();
String str2 = input.nextLine();
boolean b = input.nextBoolean();
byte b1 = input.nextByte();
short s = input.nextShort();
int i = input.nextInt();
float f = input.nextFloat();
double d = input.nextDouble();
scanner_hasNextInt();
}
public static void scanner_hasNextInt(){
Scanner input = new Scanner(System.in);
System.out.print("输入一个整数:");
if (input.hasNextInt()){
int num = input.nextInt();
System.out.println(num);
}else{
System.out.println("录入有误");
}
}
}
注意:(.next() 与 .nextLine()的区别)
- .next()可以扫描字符串数据,以"",回车,'空字符’作为结束符。
- .nextLine()可以扫描字符串数据,以回车作为结束符
常见问题:
- 当使用nextLine获取字符串前,获取数字,该字符串就获取失败,因为nextLine获取了上面回车作为结束符 导致字符串获取失败
解决:
- 将nextLine换成next(但如果字符串存在空格,则不行)
- 写两次nextLine(第一个nextLine用于获取回车符)
- 重新实例化Scanner类