1

I have a question

how can I enter char using Scanner in java?

Such as for integer number

Scanner input=new Scanner(System.in);

int a = input.nextInt();

but how can I do the same for char?

thanks for helping.

java lover
  • 9
  • 1
  • 2
  • 5

5 Answers5

2

You can do input.next(pattern) to get the next input which matches a certain pattern. If you set this to "." then it will just get the next character entered.

char c = input.next(".").charAt(0);
Eddie Curtis
  • 1,167
  • 6
  • 20
  • thanks but this is not for "char" this is for "String" because you can enter more than 1 "char" by this way but only accept the "index 0" of the "string". you can enter by this way "char c=input.nextLine().charAt(0);" but I don't want this way I want only enter "1 char" – java lover Apr 16 '14 at 04:18
2

You could take the first character from Scanner.next:

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

To consume exactly one character you could use:

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

To consume strictly one character you could use:

char c = reader.next(".").charAt(0);
takendarkk
  • 2,949
  • 7
  • 22
  • 35
ShihabSoft
  • 765
  • 5
  • 15
0

What you could do is use the Scanner to take in the single character as a String:

String s = input.next();

and then you could convert the String to a char like this:

char c = s.charAt(0);

then again, as @Elliott Frisch mentioned, you could just stop at the first line

Jeeter
  • 4,960
  • 3
  • 41
  • 64
0

If you need to read chars use InputStreamReader

    Reader input=new InputStreamReader(System.in);
    char c = (char)input.read();
Evgeniy Dorofeev
  • 124,221
  • 27
  • 187
  • 258
  • class Reader in what package? – java lover Apr 16 '14 at 04:23
  • thanks I will tested but it is the same thing like this char c=input.nextLine().charAt(0); I want to let the user only 1 char not enter the string and accpet index 0 of the string. – java lover Apr 16 '14 at 04:29
  • the difference is that reading chars is what Reader is made for, while Scanner is not designed for reading chars though you can do it using some tricks like that one – Evgeniy Dorofeev Apr 16 '14 at 04:31
0
String char
println("Password: ")
char = input.nextLine()
println(char)

The above will print all the characters the user inputs.

Das_Geek
  • 2,284
  • 7
  • 16
  • 24
Sanremy
  • 1
  • 1