In java, Write a program to process some numbers. Ask the user to enter a number
ID: 3798329 • Letter: I
Question
In java, Write a program to process some numbers.
Ask the user to enter a number and display the number, followed by ***, followed by the number squared, followed by &&&, and followed by the number cubed. Allow the user to enter as many numbers as he/she wishes. So, use a reasonable sentinel value to end the loop (for example, -999). Don’t use Yes/No type prompts to exit the loop. Also, calculate and display the total of the numbers entered by the user, total of the squares and the total of the cubes. If the user enters the sentinel value at the beginning of the process, display a message that there is nothing to process.
Explanation / Answer
import java.util.*;
public class numbers {
public static void main(String args[])
{
Scanner scan = new Scanner(System.in);
int tmp,tmp1;
int sum=0,sq_sum=0,cu_sum=0,count=0;
while(true)
{
System.out.print("Enter a number(-999 to exit):");
tmp = scan.nextInt();
if(tmp==-999)
{
break;
}
sum += tmp;
tmp1 = tmp*tmp;
sq_sum += tmp1;
cu_sum += tmp1*tmp;
count++;
}
if(count==0)
{
System.out.println("Nothing to process");
}
else
{
System.out.println("There are total of "+count+" numbers.");
System.out.println("The sum of all numbers is "+sum);
System.out.println("The sum of sqaures all numbers is "+sq_sum);
System.out.println("The sum of cubes all numbers is "+cu_sum);
}
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.