# 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

Expert's answer

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: ");

//reading input line

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.

Answer:

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

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: ");

//reading input line

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.

Answer:

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 orderand get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

## Comments

## Leave a comment