简体   繁体   English

如何从扫描仪读取单个字符?

[英]How do I read a single character from a Scanner?

I have a list of Characters and I want to add each character to the list as a user enters them (keyboard is a Scanner). 我有一个字符列表,我想在用户输入字符时将每个字符添加到列表中(键盘是扫描仪)。 I've tried two different approaches, neither works: 我尝试了两种不同的方法,但均无效:

char temp = keyboard.nextByte();
charList.add(temp);

or 要么

charList.add(keyboard.nextBye();

So how would I go about this? 那么我将如何处理呢?

If you want to just accept a char input 如果您只想接受char输入

char temp keyboard.next().charAt(0);
charList.add(temp);

Always use the second, since you don't have any idea that user may enter String. 始终使用第二个,因为您不知道用户可以输入String。 Hence the second works for both. 因此,第二种都适用。

us this Scanner reader = new Scanner(System.in); 我们这个扫描仪阅读器= new Scanner(System.in);

char c = reader.nextChar(); 字符c = reader.nextChar();

You could take the first character from Scanner.next: 您可以从Scanner.next获取第一个字符:

char c = reader.next().charAt(0); char c = reader.next()。charAt(0);

To consume exactly one character you could use: 要使用一个字符,您可以使用:

char c = reader.findInLine(".").charAt(0); char c = reader.findInLine(“。”)。charAt(0);

To consume strictly one character you could use: 要严格使用一个字符,可以使用:

char c = reader.next(".").charAt(0); char c = reader.next(“。”)。charAt(0);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM