In: Computer Science
HOW DO I ADD ON TO THIS CODE SO THAT IT DISPLAYS ALL THE VALUES INPUT BY THE USER AS SPECIFIED IN THEH FIRST PART OF THE QUESTION?
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.
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);
}
}
}
// Numbers.java
import java.util.*;
public class Numbers {
public static void main(String args[])
{
Scanner scan = new Scanner(System.in);
int tmp,tmp1, tmp2;
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;
tmp2 = tmp1*tmp;
cu_sum += tmp2;
count++;
System.out.println(tmp+" *** " + tmp1 + "
&&& " + tmp2);
}
if(count==0)
{
System.out.println("\nNothing to process");
}
else
{
System.out.println("\nThere are total of "+count+"
numbers.");
System.out.println("The sum of all numbers is "+sum);
System.out.println("The sum of squares all numbers is
"+sq_sum);
System.out.println("The sum of cubes all numbers is
"+cu_sum);
}
}
}
/*
output:
Enter a number(-999 to exit):1
1 *** 1 &&& 1
Enter a number(-999 to exit):2
2 *** 4 &&& 8
Enter a number(-999 to exit):3
3 *** 9 &&& 27
Enter a number(-999 to exit):4
4 *** 16 &&& 64
Enter a number(-999 to exit):5
5 *** 25 &&& 125
Enter a number(-999 to exit):6
6 *** 36 &&& 216
Enter a number(-999 to exit):7
7 *** 49 &&& 343
Enter a number(-999 to exit):8
8 *** 64 &&& 512
Enter a number(-999 to exit):9
9 *** 81 &&& 729
Enter a number(-999 to exit):10
10 *** 100 &&& 1000
Enter a number(-999 to exit):-999
There are total of 10 numbers.
The sum of all numbers is 55
The sum of sqaures all numbers is 385
The sum of cubes all numbers is 3025
*/