nextChar() in java

24,724

Solution 1

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

Solution 2

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)
Share:
24,724

Related videos on Youtube

hedgehogrider
Author by

hedgehogrider

I need a lot of help.

Updated on February 15, 2020

Comments

  • hedgehogrider
    hedgehogrider almost 3 years

    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!

  • jtahlborn
    jtahlborn almost 12 years
    this would only be useful if the characters were utf16 encoded. that's not a general purpose byte to char conversion utility.
  • KitsuneYMG
    KitsuneYMG almost 12 years
    @jtahlborn java.lang.String(byte[] buf, String encoding) ?
  • Solomon Ucko
    Solomon Ucko over 4 years
    What's sc's type?

Related