2

I figured out how to do it for a String and an int but I am having trouble figuring it out for char. When I try to compile it gives me an error that I have a string token for a char.

StringTokenizer stk = new StringTokenizer(line);
String name = stk.nextToken();
char sex = stk.nextToken();
int count = Integer.parseInt(stk.nextToken());
Floern
  • 33,559
  • 24
  • 104
  • 119
ttt
  • 39
  • 3

3 Answers3

1

Use String.charAt(0);

char sex = (stk.nextToken()).charAt(0);

I assume your string is something like "a b c d".

Floern
  • 33,559
  • 24
  • 104
  • 119
RahulArackal
  • 944
  • 12
  • 28
0

The nextToken() method returns a String, which is not compatible with char. If you're certain that the token will be at least one character long, you can take the first character of the String with String#charAt like so:

char sex = stk.nextToken().charAt(0);
August
  • 12,410
  • 3
  • 35
  • 51
0

You need to check the length of the String, since you only allow to put 1 character in char.

Try something like:

char c = 0;

if (name.length() == 1){
    c = name.charAt(0);
}
rbento
  • 9,919
  • 3
  • 61
  • 61
Steven
  • 475
  • 4
  • 14