Results 1 to 3 of 3
  1. #1
    katiebear128 is offline Member
    Join Date
    Sep 2011
    Posts
    54
    Rep Power
    0

    Default 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).
    Java 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??

  2. #2
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,316
    Blog Entries
    1
    Rep Power
    26

    Default 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.

  3. #3
    Junky's Avatar
    Junky is offline Grand Poobah
    Join Date
    Jan 2011
    Location
    Dystopia
    Posts
    3,789
    Rep Power
    7

    Default 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.

Similar Threads

  1. Problem with parseInt
    By fr0s1yjack in forum New To Java
    Replies: 4
    Last Post: 06-25-2011, 05:09 PM
  2. Integer.parseInt() error
    By niteangell21 in forum New To Java
    Replies: 4
    Last Post: 02-06-2011, 05:36 AM
  3. Integer.parseInt("5.843"); Error
    By Cemi in forum New To Java
    Replies: 3
    Last Post: 04-15-2010, 05:16 PM
  4. parseInt
    By trefoil in forum New To Java
    Replies: 4
    Last Post: 09-09-2009, 07:12 PM
  5. Integer.parseInt?
    By Exhonour in forum New To Java
    Replies: 4
    Last Post: 01-20-2009, 02:31 AM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •