Please use explanations for the code. Thank you. Using Scanner for User Input Wr
ID: 3862942 • Letter: P
Question
Please use explanations for the code. Thank you.
Using Scanner for User Input
Write a program that asks the user for an integer, then prints the integer, its square, and its cube to the screen.
Try computing the output in two ways:
1) without using Math.pow()
2) using Math.pow()
Use the Java API to learn what parameters Math.pow() requires.
Note: pow() is a static method of the Math class, which means that you do not need a Math object to call it. To call the pow() method, just write Math.pow(), but fill in the appropriate parameters between the ().
Challenge: Change your program to ask the user for two integers. Use Math.pow() to compute xn where x is the first integer the user enters, and n is the second integer the user enters.
Explanation / Answer
PowerRaisedToNum.java
import java.util.Scanner;
public class PowerRaisedToNum {
public static void main(String[] args) {
//Declaring the variable
int num;
//Scanner object is used to get the inputs entered by the user
Scanner sc=new Scanner(System.in);
//getting the number entered by the user
System.out.print("Enter the number :");
num=sc.nextInt();
//calculating the square and cube of number without using Math.pow()
System.out.println("** Without using Math.pow() **");
System.out.println("Square of a number :"+num*num);
System.out.println("Cube of a number :"+num*num*num);
//calculating the square and cube of number with using Math.pow()
System.out.println(" ** Using Math.pow() **");
System.out.println("Square of a number :"+(int)Math.pow(num,2));
System.out.println("Square of a number :"+(int)Math.pow(num,3));
}
}
_______________
Output:
Enter the number :5
** Without using Math.pow() **
Square of a number :25
Cube of a number :125
** Using Math.pow() **
Square of a number :25
Square of a number :125
_______________
PowerRaisedToNum1.java
import java.util.Scanner;
public class PowerRaisedToNum1 {
public static void main(String[] args) {
//Declaring the variable
int x,n;
//Scanner object is used to get the inputs entered by the user
Scanner sc=new Scanner(System.in);
//getting the number entered by the user
System.out.print("Enter the number x :");
x=sc.nextInt();
//getting the number entered by the user
System.out.print("Enter the Power n :");
n=sc.nextInt();
System.out.println(x+" rised to "+n+" is : "+(int)Math.pow(x, n));
}
}
_____________
Output:
Enter the number x :5
Enter the Power n :7
5 rised to 7 is : 78125
______________