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:07

There is no API method to get a character from the Scanner. You should get the String using scanner.next() and invoke String.charAt(0) method on the returned String.

Scanner reader = new Scanner(System.in);
char c = reader.next().charAt(0);

Just to be safe with whitespaces you could also first call trim() on the string to remove any whitespaces.

Scanner reader = new Scanner(System.in);
char c = reader.next().trim().charAt(0);
查看更多
春风洒进眼中
3楼-- · 2018-12-31 08:07
package Pack;

import java.util.Scanner;

public class test { 
    public static void main(String[] args) {

        Scanner reader = new Scanner(System.in);
        char c = reader.next(".").charAt(0);

    }
}

To get only one character char c = reader.next(".").charAt(0);

查看更多
高级女魔头
4楼-- · 2018-12-31 08:10

This actually doesn't work:

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

There are some good explanations and references in this question: Why doesn't the Scanner class have a nextChar method? "A Scanner breaks its input into tokens using a delimiter pattern", which is pretty open ended. For example when using this

c = lineScanner.next().charAt(0);

for this line of input "(1 + 9) / (3 - 1) + 6 - 2" the call to next returns "(1", c will be set to '(', and you'll end up losing the '1' on the next call to next()

Typically when you want to get a character you would like to ignore whitespace. This worked for me:

c = lineScanner.findInLine("[^\\s]").charAt(0);

Reference: regex to match a single character that is anything but a space

查看更多
浪荡孟婆
5楼-- · 2018-12-31 08:10

The easiest way is, first change the variable to a String and accept the input as a string. Then you can control based on the input variable with an if-else or switch statement as follows.

Scanner reader = new Scanner(System.in);

String c = reader.nextLine();
switch (c) {
    case "a":
        <your code here>
        break;
    case "b":
        <your code here>
        break;
    default: 
        <your code here>
}
查看更多
只若初见
6楼-- · 2018-12-31 08:15

You can solve this problem, of "grabbing keyboard input one char at a time" very simply. Without having to use a Scanner all and also not clearing the input buffer as a side effect, by using this.

char c = (char)System.in.read();

If all you need is the same functionality as the C language "getChar()" function then this will work great. The Big advantage of the "System.in.read()" is the buffer is not cleared out after each char your grab. So if you still need all the users input you can still get the rest of it from the input buffer. The "char c = scanner.next().charAt(0);" way does grab the char but will clear the buffer.

// Java program to read character without using Scanner
public class Main
{
    public static void main(String[] args)
    {
        try {
            String input = "";
            // Grab the First char, also wait for user input if the buffer is empty.
            // Think of it as working just like getChar() does in C.
            char c = (char)System.in.read();
            while(c != '\n') {
                //<do your magic you need to do with the char here>
                input += c; // <my simple magic>

                //then grab the next char
                c = (char)System.in.read();
            }
            //print back out all the users input
            System.out.println(input);
        } catch (Exception e){
            System.out.println(e);
        }
    }
}  

Hope this helpful, and good luck! P.S. Sorry i know this is an older post, but i hope that my answer bring new insight and could might help other people who also have this problem.

查看更多
还给你的自由
7楼-- · 2018-12-31 08:18

You could use typecasting:

Scanner sc= new Scanner(System.in);
char a=(char) sc.next();

This way you will take input in String due to the function 'next()' but then it will be converted into character due to the 'char' mentioned in the brackets.

This method of conversion of data type by mentioning the destination data type in brackets is called typecating. It works for me, I hope it works for u :)

查看更多
登录 后发表回答