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