Reputation: 1198
If I'm taking input with a scanner and I want to put a single character into a char type variable, what is the most efficient algorithm? I just noticed that both next() and nextLine() return strings regardless of the size, and aside from getting a string, casting it into a char array and then taking the first element, I can't think of how I would do this. There must be a more efficient way!
Upvotes: 2
Views: 28385
Reputation: 31
To read a character from input you can use the builtin function char charAt()
:
import java.util.Scanner;
Scanner sc = new Scanner(System.in);
char c = sc.next().charAt(0)
Upvotes: 3
Reputation: 2025
You could use FileChannel
to create a ByteBuffer
. Once here you can then call the asCharBuffer()
method to return a char buffer.
Here's a decent example: Example using CharBuffers
Upvotes: 2