0

How would you go about skipping non-numeric characters in a string and only adding the sum of the numbers a multi line string?

1
Contributor
2
Replies
3
Views
6 Years
Discussion Span
Last Post by Latvija13
0

I think I've made some progress. I can at least know which index values in my string are numbers. But I'm not sure how to actually get those values. I'm getting 199 for the sum, I'm really not sure where that is coming from since my indexes that are numbers are only 4,10,16 and 20.

String test = "Word1 Word2 Word3\nW 1";
          Scanner scan = new Scanner(test);
          int sum = 0;
            for(int i = 0;i<test.length();i++){
                if(Character.isDigit(test.charAt(i))){
                    System.out.println(i);
                    sum += test.charAt(i);
                }
            }
            System.out.println("sum = "+sum);
0

Nevermind. I got it. I guess I wasn't quite on the right track.

This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.