64 484
Assignments Done
99,1%
Successfully Done
In September 2018

Answer to Question #60103 in Java | JSP | JSF for saptak

Question #60103
given a set of integers(separated by spaces). Print the sum of their cubes
Solution:
The code that solves the task:

import java.util.Scanner;

public class q60103 {

public static void main(String[] args) {

int num,sum=0;
System.out.println("Input integers: ");
Scanner in = new Scanner(System.in);
String data= in.nextLine();

//analyzing each integer in the line
Scanner scan = new Scanner(data);
while( scan.hasNextInt() ) // is there more data to process?
{
num = scan.nextInt();
sum = sum+num * num * num;
}
System.out.println("The sum of cubes is " + sum);

}
}

As soon an the code encounters incorrect input, it ignores it. See following outputs for examples.

Some examples of input-output:

Input integers:
1 2 3
The sum of cubes is 36

Input integers:
5 6 7 0
The sum of cubes is 684

Examples of handling incorrect input:
Input integers:
1 2 khhdgsvgl
The sum of cubes is 9

Input integers:
dsgsgsdgs
The sum of cubes is 0

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!