Prompt a user to enter a series of integers separated by spa
Prompt a user to enter a series of integers separated by spaces and accept the input as a String. Display the list of integers and their sum. Save the file as SumIntegersInString.java.
I have tried the following code, but it just runs continuously with no opportunity for input.
import java.io.*;
import java.util.Scanner;
class SumIntegersInString
{
public static void main(String args[])
{
Scanner in = new Scanner(System.in);
String input = in.nextLine();
int sum = 0;
for(String value : input.split(\" \"))
{
System.out.print(value + \" \");
sum += Integer.parseInt(value);
}
System.out.println(\"Sum:\" + sum);
}
}
Solution
import java.io.*;
import java.util.Scanner;
public class SumIntegersInString
{
public static void main(String args[])
{
// statement to prompt the user for a series of integers
System.out.print(\"Enter a series of integers separated by a space: \");
Scanner in = new Scanner(System.in);
String input = in.nextLine();
int sum = 0;
for(String value : input.split(\" \"))
{
System.out.print(value + \" \");
sum += Integer.parseInt(value);
}
System.out.println(\"\ Sum:\" + sum);
}
}
