James Parker James Parker - 5 days ago 4
Java Question

Java explicit type cast for the floating-point division

I am not sure if I am using explicit type cast for the floating-point division in option 4 (Division). I need a little help understanding what is floating-point division.

I must use integers to store the 2 operands, a double to store the result. You must use an explicit type cast for the floating-point division in option 4. Also use a switch statement to process the menu choices. After each computation

import java.util.Scanner;

public class SimpleCalculator
{
//-----------------------------------------------------------------
// Calculates two integers
// using values entered by the user.
//-----------------------------------------------------------------
public static void main(String[] args)
{
//Variables
final int ADDITION = 1,SUBTRACTION = 2, MULTIPLICATION = 3,DIVISION = 4, EXIT = 5;
int num1 = 0, num2 = 0, choice = 0;
double dblNum1, dblNum2, result;
String equation = "";

do
{
//Processing
equation = "";
Scanner scan = new Scanner(System.in);
System.out.println("Choose from the following: ");
System.out.println("1. Add 2 integers");
System.out.println("2. Subtract 2 integers");
System.out.println("3. Multiply 2 integers");
System.out.println("4. Divide 2 integers");
System.out.println("5. Exit");
System.out.print("Enter choice: ");

choice = scan.nextInt();

if(choice < 5 && choice > 0)//keeps program from asking for two numbers if exiting
{
System.out.print("Enter first integer: ");
num1 = scan.nextInt();

System.out.print("Enter second integer: ");
num2 = scan.nextInt();
}

//switch for operations
switch (choice)
{
case ADDITION:
result = num1 + num2;
equation = ((num1) + " + " + (num2) + " = "+ result);
break;

case SUBTRACTION:
result = num1 - num2;
equation = ((num1) + " - " + (num2) + " = "+ result);
break;

case MULTIPLICATION:
result = num1 * num2;
equation = ((num1) + " * " + (num2) + " = "+ result);
break;

case DIVISION:
if(num2 == 0)//when denominator becomes zero
{
System.out.println("DIVISION NOT POSSIBLE");
break;
}
dblNum1 = num1;//convert int to double
dblNum2 = num2;
result = dblNum1/dblNum2;
equation = ((num1) + "/" + (num2) + " = "+ result);
break;

case EXIT:
System.exit(0);
break;

default:
System.out.println("YOU HAVE ENTERED AN INCORRECT CHOICE");
}
//Output
System.out.println(equation);
System.out.println();
}while(choice != EXIT);
}
}

Answer

No, that's not an explicit typecast. You would want to use something like this:

result = ((double) num1) / ((double) num2);

Actually, because of the widening rules for the / operator, you would only need one of those explicit casts, but there's no harm in having both. In fact, because the cast operator () has higher precedence than the division operator /, you could write it as:

result = (double) num1 / num2;

which combines an explicit cast of the numerator and an implicit cast of the denominator.

Comments