darsha
darsha

Reputation: 61

Error in Calculating sum of particular column

i am here with another problem in my code since i am new to java. my task is to read a text file that contains some 300 records and record has 13 fields . i am trying to calculate the sum of each field for example, if age is my first field them sum of the age of all 300 people and then store it in an array index.

import java.io.*;
import java.util.Vector;
public class Mean
{
private static Vector contents;

private static BufferedReader br;
private static FileInputStream inputstream;
private static FileOutputStream outputstream;

public Mean()
{
    contents = new Vector();
}
public void doDuplicationRemoval(String filename)
{
    try{
        inputstream = new FileInputStream(filename);
        br = new BufferedReader(new InputStreamReader(inputstream));
        String string = "";
        while((string = br.readLine())!= null)
        {
            String[] split = string.split(",");
            Vector vector = new Vector();
            for(int i=0; i<split.length; i++)
                vector.add(split[i].trim());
            if(!vector.contains("?"))
    {
        contents.add(split);
    }


    }
    }
    catch(Exception err){
        System.out.println(err);
    }
}

 public void doDataConv(String filename)
{
    DataConversion.readFile(contents);
    DataConversion.writeFile(filename);
}

  public static void doDataConversion(Vector contents)
{
    DataConversion.readFile(contents);
    for(int i=0; i<contents.size(); i++)
    {
        String string = "";
        String[] split = (String[])contents.get(i);
        split[0] += getAge(split[0]);
        System.out.println(split[0]);
}
}
  private static String getAge(String src)
{
    String age = src;
    return age;
}

public static void main(String [] args) {
    Mean dr;
    dr = new Mean();
    dr.doDuplicationRemoval("input.txt");
    dr.doDataConv("inp_out.txt");
dr.doDataConversion(contents);
}


}

the input is
63
67
50

my aim is to get output as 180

but am getting
6363
6767
5050

can someone help me to fix the problem.

Upvotes: 1

Views: 211

Answers (4)

Hemant Metalia
Hemant Metalia

Reputation: 30638

your actual error is here as you are using + to add two string which contains integer

split[0] += getAge(split[0]);//here split[0] is String 63, getAge(split[0]) 
                     //retuns also String 63 hence addition  gives "63" + "63" = "6363"

doing string addition that is concatenation

Integer.parseInt()

so make conversion as follow:

split[0] = new Integer (Integer.parseInt(split[0]) +
                          Integer.parseInt( getAge(split[0]))).toString()

if you want to store values in integer array then make another array of integer to store values.

if you want to store result in int array then do as follow:

int agesum[] = new int[]

agesum[0] += Integer.parseInt( getAge(split[0]));

Upvotes: 0

Alexis Dufrenoy
Alexis Dufrenoy

Reputation: 11946

The problem is you line

split[0] += getAge(split[0]);

As the type of your split table is String, it will concatenate the values. You need a result table, like:

int[] result = new int[];

And then:

result[0] += getAge(split[0]);

I will try to formulate a good design for your purpose:

  • Create a class with the structure of a record. Let's name it Record
  • Instanciate a Record object with each line you read
  • Put in a Record table
  • You can create another Record with all the sums
  • Don't use Vector. If you need a list, use ArrayList (except in a multithreaded context). Vector is just a legacy class from before Java 2. It's obsolete.

Upvotes: 0

Jon Skeet
Jon Skeet

Reputation: 1499770

This looks like the first problem to me:

private static String getAge(String src)
{
    String age = src;
    return age;
}

You're treating the age as a string. If you want to treat it as a number, you should be parsing it (e.g. with Integer.parseInt).

Here's the second problem:

String string = "";
String[] split = (String[])contents.get(i);
split[0] += getAge(split[0]);
System.out.println(split[0]);

That's only ever changing the value of split[0], which is then overwritten when you reassign it in the next iteration. You need something like:

int sum = 0;
for(int i=0; i<contents.size(); i++)
{
    String[] split = (String[])contents.get(i);
    sum  += getAge(split[0]); // After changing getAge to return an int
}
System.out.println(sum);

Upvotes: 1

Andreas Dolk
Andreas Dolk

Reputation: 114757

Your not adding numbers but concatenating Strings:

split[0] += getAge(split[0]);

To sum up the values (e.g. the numeric content of your first column fields)

  1. Define a local variable, like int sum = 0; outside the loop
  2. parse the values from the Strings (Integer.parseInt(split[0])) and
  3. add every parsed value to sum.

Upvotes: 1

Related Questions