In: Computer Science
Create a Java method that does the following:
1) Ask the user for a dividend and a divisor both of "int" type.
2) Computes the remainder of the division. The quotient (answer) must be of the "int" type.
Do NOT use the method " % " provided in Java in your code. Remember that it gives wrong answers when some of the inputs are negative. Please see the videos for the explanation.
import java.util.*;
public class Main
{
//Method to compute the remainder of the
division
static int getRemainder()
{
int remainder = 0;
Scanner input = new Scanner(System.in);
//Input the divident from user
System.out.print("Please enter the divident: ");
int divident = input.nextInt();
//Input the divisor from user
System.out.print("Please enter the divisor: ");
int divisor = input.nextInt();
// Case I: Divisor equals to 0
if (divisor == 0)
{
System.out.println("ERROR !! Divisor cannot be zero !");
return -1;
}
// Case II: Divident equals to 0
if (divident == 0)
{
remainder = 0;
return remainder;
}
// Case III: Divisor and/or Divident is negative
if (divisor < 0)
divisor = -divisor;
if (divident < 0)
divident = -divident;
// Loop to find the largest multiple of divisor that is less than
or equal to divident
int i = 1, multiple = 0;
while ((multiple + divisor) <= divident)
{
multiple = divisor * i;
i++;
}
remainder = divident - multiple;
return remainder;
}
// Driver method
public static void main(String[] args)
{
int remainder = getRemainder();
// Prints the remainder
if (remainder != -1)
System.out.print("The remainder of the division is " +
remainder);
}
}