Ask the user to enter a series of numbers separated by commas. Write code to dis
ID: 3638184 • Letter: A
Question
Ask the user to enter a series of numbers separated by commas. Write code to display the sum of all the numbers:Enter a series of numbers: 10,20,30
Sum: 60
I have the majority of the code done, but can't seem to get the sum to work, and bad thing is i know why. We have to use the String Split method, and of course the problem with that is the array that stores the split of 10 20 and 30 is in String format. I have tried and tried to find a way to parse the String Array one at a time, but get errors. The code below does nothing more than combine the array as it would a string, doesn't give the total. Would love some help with getting the code below to perform addition not concatenation.
import java.util.Scanner;
public class splitmethod {
public static void main(String[] args) {
//establish scanner item
Scanner kb = new Scanner(System.in);
//establish variables to store user input and sum
String userNumber;
String sum = null;
//get numbers from user and store
System.out.println("Enter some numbers seperated by coma's: ");
userNumber = kb.nextLine();
//set up a split method array for the entered numbers that takes out comma's
String [] tokens = userNumber.split("[, ]");
//cycle through the split method array and get sum of numbers
for (int i = 0; i < tokens.length; i++)
{
System.out.println(tokens[i]);
sum = tokens[i];
}
//print out the sum
System.out.println("Sums is: " + sum);
}
}
Explanation / Answer
import java.util.Scanner; public class splitmethod { public static void main(String[] args) { //establish scanner item Scanner kb = new Scanner(System.in); //establish variables to store user input and sum String userNumber; int sum = 0; //get numbers from user and store System.out.println("Enter some numbers seperated by coma's: "); userNumber = kb.nextLine(); //set up a split method array for the entered numbers that takes out comma's String [] tokens = userNumber.split("[, ]"); //cycle through the split method array and get sum of numbers for (int i = 0; iRelated Questions
Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.