ttt
ttt

Reputation: 39

How to make a Stingtokenizer for a char

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());

Upvotes: 2

Views: 1394

Answers (3)

Steven
Steven

Reputation: 525

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);
}

Upvotes: 0

RahulArackal
RahulArackal

Reputation: 954

Use String.charAt(0);

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

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

Upvotes: 1

August
August

Reputation: 12558

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);

Upvotes: 0

Related Questions