Take a char input from the Scanner

2018-12-31 08:04发布

I am trying to find a way to take a char input from the keyboard.

I tried using:

Scanner reader = new Scanner(System.in);
char c = reader.nextChar();

This method doesn't exist.

I tried taking c as a String. Yet, it would not always work in every case, since the other method I am calling from my method requires a char as an input. Therefore I have to find a way to explicitly take a char as an input.

Any help?

20条回答
不流泪的眼
2楼-- · 2018-12-31 08:19

Setup scanner:

reader.useDelimiter("");

After this reader.next() will return a single-character string.

查看更多
裙下三千臣
3楼-- · 2018-12-31 08:21

Try this: char c=S.nextLine().charAt(0);

查看更多
后来的你喜欢了谁
4楼-- · 2018-12-31 08:22

Try this

Scanner scanner=new Scanner(System.in);
String s=scanner.next();
char c=s.charAt(0);
查看更多
路过你的时光
5楼-- · 2018-12-31 08:25
import java.io.*;

class abc // enter class name (here abc is class name)
{
    public static void main(String arg[])
    throws IOException // can also use Exception
    {
        BufferedReader z =
            new BufferedReader(new InputStreamReader(System.in));

        char ch = (char) z.read();
    } // PSVM
} // class
查看更多
浪荡孟婆
6楼-- · 2018-12-31 08:26

Just use...

Scanner keyboard = new Scanner(System.in);<br>
char c = keyboard.next().charAt(0);

That's it...

查看更多
栀子花@的思念
7楼-- · 2018-12-31 08:28

You should use your custom input reader for faster results instead of extracting first character from reading String. Link for Custom ScanReader and explanation: https://gist.github.com/nik1010/5a90fa43399c539bb817069a14c3c5a8

Code for scanning Char :

BufferedInputStream br=new BufferedInputStream(System.in);
char a= (char)br.read();
查看更多
登录 后发表回答