Results 1 to 5 of 5
- 11-14-2011, 11:33 PM #1
Member
- Join Date
- Sep 2011
- Posts
- 54
- Rep Power
- 0
StringTokenizer, making a method help
Suppose an external file is made up entirely of integers. In the model we've been using in this unit, the file is actually read in, line by line, as a sequence of Strings. Using a StringTokenizer inside processLine() method can produce individual tokens that look like numbers, but are actually Strings that are composed of digits. To convert each token from String format to integer format, you need to use the parseInt() method from the Integer class. Thus
int birthYear = Integer.parseInt("1983");
correctly stores the integer 1983 into the birthYear integer variable.
For this assignment you should create a complete processLine method in the EchoSum class, so that it transforms each number in each line to integer format, and then sums the entries on the line and prints their sum on a separate line. For example, if the external text file looks like this:
1 2 3 4
3 4 7 1 11
2 3
your program should display this:
10
26
5
Right now it says runtime error, java.lang.NumberFormatException...Java Code:public void processLine(line){ int sum=0; StringTokenizer s=new StringTokenizer(line); while(s.hasMoreTokens()){ int i=Integer.parseInt(line); sum+=i; } System.out.println(sum);
I'm wondering how I can fix my code to do what its supposed to do, I would really appreciate any help!
- 11-14-2011, 11:34 PM #2
Moderator
- Join Date
- Jul 2010
- Location
- California
- Posts
- 1,608
- Rep Power
- 5
Re: StringTokenizer, making a method help
Given your input, the above would be similar to:int i=Integer.parseInt(line);
Try it and see if this works. Are you sure you want to parse the line, or parse the token from the tokenizer?Java Code:int i=Integer.parseInt("1 2 3 4");
- 11-14-2011, 11:41 PM #3
Member
- Join Date
- Sep 2011
- Posts
- 54
- Rep Power
- 0
Re: StringTokenizer, making a method help
I tried int i=Integer.parseInt(s); but it said error. Should I try it again?
- 11-14-2011, 11:44 PM #4
- 11-14-2011, 11:52 PM #5
Member
- Join Date
- Sep 2011
- Posts
- 54
- Rep Power
- 0
Similar Threads
-
making method, repurposing
By katiebear128 in forum New To JavaReplies: 5Last Post: 10-27-2011, 03:21 PM -
Java stringtokenizer- making it reverse word
By katiebear128 in forum New To JavaReplies: 8Last Post: 10-20-2011, 12:15 AM -
Making a method exercise question
By katiebear128 in forum New To JavaReplies: 6Last Post: 10-01-2011, 08:48 PM -
Help regarding StringTokenizer
By mahesh19nov in forum New To JavaReplies: 3Last Post: 10-26-2010, 09:25 AM -
Help with StringTokenizer!
By ookie833 in forum New To JavaReplies: 13Last Post: 12-14-2008, 04:09 PM


1Likes
LinkBack URL
About LinkBacks
Reply With Quote

Bookmarks