2

How would I remove the chars from the data in this file so I could sum up the numbers?

Alice Jones,80,90,100,95,75,85,90,100,90,92
Bob Manfred,98,89,87,89,9,98,7,89,98,78

I want to do this so for every line it will remove all the chars but not ints.

0

7 Answers 7

1

The following code might be useful to you, try running it once,

public static void main(String ar[])
{
    String s = "kasdkasd,1,2,3,4,5,6,7,8,9,10";

    int sum=0;
    String[] spl = s.split(",");
    for(int i=0;i<spl.length;i++)
    {
        try{
            int x = Integer.parseInt(spl[i]);
            sum = sum + x;
        }
        catch(NumberFormatException e)
        {
            System.out.println("error parsing "+spl[i]);
            System.out.println("\n the stack of the exception");
            e.printStackTrace();
            System.out.println("\n");
        }
    }   
    System.out.println("The sum of the numbers in the string : "+ sum);
}

even the String of the form "abcd,1,2,3,asdas,12,34,asd" would give you sum of the numbers

Sign up to request clarification or add additional context in comments.

Comments

0

You need to split each line into a String array and parse the numbers starting from index 1

String[] arr = line.split(",");
for(int i = 1; i < arr.length; i++) {
   int n = Integer.parseInt(arr[i]);
   ...

Comments

0

try this:

  String input = "Name,2,1,3,4,5,10,100";
  String[] strings = input.split(",");
  int result=0;
  for (int i = 1; i < strings.length; i++)
  { 
    result += Integer.parseInt(strings[i]);
  }

8 Comments

When I try to print this onto the console it gives me null, do you know why?
Show us your print statement
String[] strings = strLine.split(","); int result=0; for (int i = 1; i < strings.length; i++) { result += Integer.parseInt(strings[i]); } System.out.println(result);
I'm very new to Java and I come from Python, and thank you for the help in advance.
That's extremely weird. If result is an int, it shouldn't be possible for println() to print "null" for its value.
|
0

You can make use of the split method of course, supplying "," as the parameter, but that's not all.

The trick is to put each text file's line into an ArrayList. Once you have that, move forwars the Pseudocode:

1) Put each line of the text file inside an ArrayList 2) For each line, Split to an array by using "," 3) If the Array's size is bigger than 1, it means there are numbers to be summed up, else only the name lies on the array and you should continue to the next line 4) So the size is bigger than 1, iterate thru the strings inside this String[] array generated by the Split function, from 1 to < Size (this will exclude the name string itself)

5) use Integer.parseInt( iterated number as String ) and sum it up

There you go

Number Format Exception would occur if the string is not a number but you are putting each line into an ArrayList and excluding the name so there should be no problem :)

1 Comment

people posting source code are not worthy of upvote , nice explanation dude . :)
0

Well, if you know that it's a CSV file, in this exact format, you could read the line, execute string.split(',') and then disregard the first returned string in the array of results. See Evgenly's answer.

Edit: here's the complete program:

class Foo {
  static String input = "Name,2,1,3,4,5,10,100";
  public static void main(String[] args) {
    String[] strings = input.split(",");
    int result=0;
    for (int i = 1; i < strings.length; i++)
    { 
      result += Integer.parseInt(strings[i]);
    }
    System.out.println(result);
  }
}

(wow, I never wrote a program before that didn't import anything.)

And here's the output:

125

If you're not interesting in parsing the file, but just want to remove the first field; then split it, disregard the first field, and then rejoin the remaining fields.

String[] fields = line.split(',');
StringBuilder sb = new StringBuilder(fields[1]);
for (int i=2; i < fields.length; ++i)
    sb.append(',').append(fields[i]);
line = sb.toString();

You could also use a Pattern (regular expression):

line = line.replaceFirst("[^,]*,", "");

Of course, this assumes that the first field contains no commas. If it does, things get more complicated. I assume the commas are escaped somehow.

2 Comments

Yes it is a CSV file and I used his code, I think it works but when I try to print 'result' it gives me null.
BTW, I left it out of my code for simplicity, but you should always wrap parseInt() in a try..catch block in case it receives malformed input and throws an exception.
0

There are a couple of CsvReader/Writers that might me helpful to you for handling CSV data. Apart from that:

  • I'm not sure if you are summing up rows? columns? both? in any case create an array of the target sum counters int[] sums(or just one int sum)
  • Read one row, then process it either using split(a bit heavy, but clear) or by parsing the line into numbers yourself (likely to generate less garbage and work faster).
  • Add numbers to counters
  • Continue until end of file

Loading the whole file before starting to process is a not a good idea as you are doing 2 bad things:

  1. Stuffing the file into memory, if it's a large file you'll run out of memory (very bad)
  2. Iterating over the data 2 times instead of one (probably not the end of the world)

Comments

0

Suppose, format of the string is fixed.

        String s = "Alice Jones,80,90,100,95,75,85,90,100,90,92";

At first, I would get rid of characters

        Matcher matcher = Pattern.compile("(\\d+,)+\\d+").matcher(s);
        int sum = 0;

After getting string of integers, separated by a comma, I would split them into array of Strings, parse it into integer value and sum ints:

        if (matcher.find()){
            for (String ele: matcher.group(0).split(",")){
                sum+= Integer.parseInt(ele);
            }
        }
        System.out.println(sum);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.