nextChar() in java
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 asid开发者_Go百科e 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!
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)
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
精彩评论