-
error w/ parseInt
Given String s="103 2", I'm trying to use StringTokenizer to produce individual tokens that look like numbers, but must be converted from string to int using parseInt() method. Then it sums the entries of string s on a separate line (so it will print 105).
Code:
import java.util.*;
public class processLine{
public static void main (String[] args){
String s="103 2";
StringTokenizer st=new StringTokenizer(s);
while(st.hasMoreTokens())
{String k=st.nextToken();
String b=st.nextToken();
Integer.parseInt(k);
Integer.parseInt(b);
int sum=k+b; //error here(incompatible types). found:java.lang.String. required: int
System.out.println(sum);}
}
}
Why is that error there? I thought I converted the strings to int w/ parseInt??
-
Re: error w/ parseInt
Strings are immutable, and nothing you do changes them. When the Integer.parseInt(...) is called, it does nothing to the String that is passed into the method parameter, but instead it returns an int result that you can use. So I suggest you create variables to catch the returns from these methods and use them.
-
Re: error w/ parseInt
Do not call nextToken more than once inside the loop. It will crash and burn if you have an odd number of tokens.