从Java 1.5开始引入Scanner类。此类接受File,InputStream,Path和String对象,使用正则表达式逐个令牌读取所有原始数据类型和String(从给定的源)令牌。默认情况下,空格被视为定界符(将数据分成令牌)。
使用Scanner类读取字符
Scanner类提供nextXXX()(其中xxx是int,float,boolean等)方法,这些方法用于读取各种原始数据类型。但是它从来没有提供读取单个字符的方法。
但是,您仍然可以使用此类读取单个字符。next()Scanner类的方法以String格式返回源的下一个标记。这会将单个字符(由定界符分隔)读取为字符串。String str = sc.next();toCharArray()String类的方法将当前String转换为字符数组。char ch[] = str.toCharArray()从数组中可以获取存储在第0个位置的字符。char myChar = ch[0];
示例
以下示例使用Scanner类从用户读取单个字符。import java.util.Scanner;
public class ContentsOfFile {
public static void main(String args[]) throws Exception {
//创建扫描仪对象
Scanner sc = new Scanner(System.in);
//创建一个StringBuffer对象
System.out.println("Enter your grade: (A, B, C, D)");
char grade = sc.next().toCharArray()[0];
if(grade == 'A'){
System.out.println("You are very good, you have been promoted");
}else if(grade=='B'){
System.out.println("You are good, you have been promoted");
}else if(grade=='C'){
System.out.println("You are average, you have been " + "promoted, you need to work hard");
}else if(grade=='D'){
System.out.println("You are not promoted, try again");
}else {
System.out.println("Improper input");
}
}
}
输出结果Enter your grade: (A, B, C, D)
C
You are average, you have been promoted, you need to work hard