Yahoo Answers is shutting down on May 4th, 2021 (Eastern Time) and beginning April 20th, 2021 (Eastern Time) the Yahoo Answers website will be in read-only mode. There will be no changes to other Yahoo properties or services, or your Yahoo account. You can find more information about the Yahoo Answers shutdown and how to download your data on this help page.

Java question about split() method?

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. Use String method split inside processLine() to 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 static 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

import java.io.*;

public class EchoSum extends Echo

{

public EchoSum (String datafile) throws IOException

{

super(datafile);

}

// This is my attempted code:

public void processLine(String line){

int sum= 0;

StringTokenizer answer= new StringTokenizer(line);

while(answer.hasMoreTokens()){

int k = Integer.parseInt(answer.nextToken());

sum+= k;

System.out.println(sum);

}

I'm getting a compilation error saying that it could not find the symbol "StringTokenizer", and I think this is because our teacher wants us to use the split()

Update:

Here is my attempt with the split method:

public void processLine(){

int sum= 0;

String[] answer= line(" ");

int x= Integer.parseInt(answer.nextLine());

for(int k= 0; k < answer.length; k ++){

sum+= k;

}

System.out.println(sum);

}

^ This probably SCREAMS "idiot", but i dont know what I'm doing. I

1 Answer

Relevance
  • John
    Lv 7
    4 years ago

    Your the first attempted is correct. However you have to import java.util.StringTokenizer after importing java.io;

    import java.util.StringTokenizer;

    private void processLine(String line) {

    int sum = 0;

    StringTokenizer st = new StringTokenizer(line);

    while(st.hasMoreElements()) {

    sum += Integer.parseInt(st.nextToken());

    }

    System.out.println(sum);

    }

Still have questions? Get your answers by asking now.