I want to input a single character of type char
in a Java program. Even if the user enters more than one character, it should only take the first. How can I do this? Is it possible with the help of the Scanner
class?
There are two ways to do that:
char c = scanner.nextLine().charAt(0);
Which will read the first available line, and extract the first character, or
try {
char c = (char) System.in.read();
} catch (IOException e) {
e.printStackTrace();
}
Which will read the first byte
in the first available line and cast it to a char
What's wrong with
scanner.next().charAt(0)
Or, here's another idea, if you don't want next()
to return anything extra:
scanner.useDelimiter("")
Now scanner.next()
should return a single character string, and you can use .charAt(0)
as needed.
要使用Scanner
的单个字符,可以使用:
char ch = scanner.findInLine(".").charAt(0);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.