如何在Java中使用Scanner类读取单个字符?
从Java 1.5开始引入了Scanner类。此类接受File、InputStream、Path和String对象,使用正则表达式逐个标记读取所有基本数据类型和字符串(来自给定源)。默认情况下,空格被视为分隔符(将数据分成标记)。
使用Scanner类读取字符
Scanner类提供nextXXX()方法(其中xxx是int、float、boolean等),用于读取各种基本数据类型。但它从未提供读取单个字符的方法。
但是,您仍然可以使用此类读取单个字符。
- Scanner类的next()方法以字符串格式返回源的下一个标记。这将读取单个字符(由分隔符分隔)作为字符串。
String str = sc.next();
- String类的toCharArray()方法将当前字符串转换为字符数组。
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 { //Creating a Scanner object Scanner sc = new Scanner(System.in); //Creating a StringBuffer object 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
广告