-3

My challenge is to find the total value of the elements within a string with user input. Input by user should be as follows: 1,2,3,4,5,6,7...

I am running into issues when I tried to use StringTokenizer so I went with the split() method but the total amount is off by 7 or by 28 depending on whether I use (i + i) or (+=i) in second for loop.

// Libraries
import java.util.Scanner;
import java.util.StringTokenizer;

public class Project_09_8
{

    public static void main(String[] args) 
    {

    // Create instance of Scanner class
    Scanner kb = new Scanner(System.in);

    // Variables
    String input;                       // Holds user input
    String [] result;                   // Holds input tokens in an array
    int i = 0;                          // Counter for loop control

    // User input
    System.out.print("Please enter a positive whole number, separated by commas: ");
    input = kb.nextLine();
    result = input.split(",");

    // Converts input String Array to Int Array
    int [] numbers = new int [result.length];                

    // Loop through input to obtain each substring
    for (String str: result) {
        numbers[i] = Integer.parseInt(str);
        i++;
    }

    // Receive this output when printing to console after above for loop [I@10ad1355. 

    /*
    // Loop to determine total of int array
    int sum = 0;                        // Loop control variable
    for (int j : numbers) {
         sum += i;
         //sum = i + i;                
     }

    // Print output to screen
    System.out.println("\nThe total for the numbers you entered is: " + sum);
    */

    } // End main method

} // End class
Kick Buttowski
  • 6,709
  • 13
  • 37
  • 58
ml24
  • 1
  • 3
  • What are you adding to `sum`? I think your program has a major typo. – ajb Oct 20 '14 at 19:09
  • 3
    don't you want `sum += j`? – Ben Oct 20 '14 at 19:09
  • @ ajb - You are correct. Can't believe I didn't see that. @ Ben - Yes, I meant to use sum += j instead of i. Once I changed it, it worked correctly. – ml24 Oct 20 '14 at 19:12

3 Answers3

2

In Java 8 , you can put yourself out of misery

Code:

String s = "1,2,3,4,5,6,7";
String[] sp = s.split(",");
//Stream class accept array like Stream.of(array)
// convert all String elements to integer type by using map
// add all elements to derive summation by using reduce 
int sum = Stream.of(sp)
                .map( i -> Integer.parseInt(i))
                .reduce(0, (a,b) -> a+b);
System.out.println(sum);

output:

28
Kick Buttowski
  • 6,709
  • 13
  • 37
  • 58
1

Since you are already using Scanner you can use the useDelimiter method to split on commas for you.

Scanner also has a nextInt() to do the parsing /converting from String to int for you

    Scanner s = new Scanner(System.in)
                    .useDelimiter("\\s*,\\s*");
    int sum = 0;
    while(s.hasNextInt()){
         sum += s.nextInt();
    }
    System.out.println(sum);
dkatzel
  • 31,188
  • 3
  • 63
  • 67
0

I suggest you split on (optional) whitespace with \\s*,\\s*, declare variables when you need them and add the sum in one loop (without converting to an int[] copy) like,

public static void main(String[] args) {
    // Create instance of Scanner class
    Scanner kb = new Scanner(System.in);
    System.out.print("Please enter a positive whole number, "
        + "separated by commas: ");
    String input = kb.nextLine();
    String[] result = input.split("\\s*,\\s*");
    int sum = 0;
    for (String str : result) {
        sum += Integer.parseInt(str);
    }
    System.out.println(Arrays.toString(result));
    System.out.printf("The sum is %d.%n", sum);
}
Elliott Frisch
  • 198,278
  • 20
  • 158
  • 249