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.
This looks like the first problem to me:
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:
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: