In: Computer Science
1) Question with methods use scanner:
1) Create one method that will add four numbers (return method or
regular public static void )
2) Create another method that will subtract four numbers (return
method or regular public static void )
3) Create another method that will multiplay four numbers (return
method or regular public static void )
4) Create another method that will divide four numbers (return
method or regular public static void )
5) Create another method that will find average of four numbers
(return method or regular public static void )
6) In main method (Two parts):
1) Call four System prompt to enter numbers and four variables that
will relate to scanner (they should be consistent with
variables declared in above methods).
2) Display results even with system.out.print assigned in main
method or in your methods above?
Refer to code snippet below. Ask any doubts or clarifications in comments section.
import java.util.Scanner;
public class Answer {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter first number: "); //get first number
int a = sc.nextInt();
System.out.println("Enter second number: "); //get second
int b = sc.nextInt();
System.out.println("Enter third number: "); //get third
int c = sc.nextInt();
System.out.println("Enter fourth number: ");//get fourth
int d = sc.nextInt();
addNums(a, b, c, d); //call addNums method
subtractNums(a, b, c, d);//call subtractNums method
multiplyNums(a, b, c, d); //call multiplyNums method
divideNums(a, b, c, d); //call divideNums method
averageNums(a, b, c, d);// call averageNums method
}
public static void addNums(int a, int b, int c, int d)
{
int result = a+b+c+d; //add
System.out.println("Sum of 4 numbers is : "+result); //print value
}
public static void subtractNums(int a, int b, int c, int d)
{
int result = a-b-c-d; //subtract
System.out.println("Difference of 4 numbers is : "+result);//print value
}
public static void multiplyNums(int a, int b, int c, int d)
{
int result = a*b*c*d; //multiply
System.out.println("Product of 4 numbers is : "+result);//display
}
public static void divideNums(int a, int b, int c, int d)
{
double result = (double) a/b/c/d; //divide
System.out.printf("Division of 4 numbers is : %.2f\n", result); //display
}
public static void averageNums(int a, int b, int c, int d)
{
double result = (a+b+c+d)/4; //find average
System.out.println("Average of 4 numbers is : "+result); //display
}
}
Output:
Refer to output above. Thanks.