Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting separate characters from a java Scanner

Tags:

java

In Java's Scanner class, why does the syntax nextChar() not exist, and is there a command would do something similar with out using the String variable?

like image 553
Damion Deslaurier Avatar asked Jun 28 '26 09:06

Damion Deslaurier


2 Answers

Two solutions:

  • use toCharArray(): this will return a char[] over which you can use a foreach loop;
  • use the string length in combination with .charAt().
like image 194
fge Avatar answered Jun 29 '26 22:06

fge


Java's Scanner class operates on tokens, complete units of output. This is usually complete words, lines of text, numbers (integers, doubles, floats, etc). If you want to read individual characters, you should use BufferedReader in a construct like this

BufferedReader in = new BufferedReader(new InputStreamReader(System.in));

Replacing System.in with whatever input you're using for Scanner. Then use char c = (char)in.read() to read the next character from the input.

like image 38
Peter Elliott Avatar answered Jun 29 '26 23:06

Peter Elliott



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!