Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Prompt a user to enter a series of integers separated by spaces and accept the i

ID: 3797954 • Letter: P

Question

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);
  
}
}

Explanation / Answer

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);
  
}
}