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.
Here is the code that I have so far I can't seem to get it correct. Here is the feedback from the instructor: It appears you are computing the quotient here. This program is supposed to compute the remainder. This can be fixed easily with one line of code.
Which line of code needs to be corrected to determine the remainder?
import java.util.Scanner;
public class Main {
//method to get the floor value
static int floorDivide(int a, int b)
{
if(a % b != 0 && ((a < 0 && b > 0) || (a > 0 && b < 0)))
{
return (a / b - 1);
}
else
{
return (a / b);
}
}
public static void main(String args[]) {
int a,b, result;
Scanner sc=new Scanner(System.in);
System.out.println("Please Enter a Dividend: ");
a=sc.nextInt();
System.out.println("Please Enter a Divisor: ");
b=sc.nextInt();
result= floorDivide(a,b);
System.out.println("The Result is: "+result);
}
}
If you need any corrections/clarifications kindly comment.
Please give a Thumps Up if you like the answer.
Program
import java.util.Scanner;
public class Division
{
//method to get the floor value
static int floorDivide(int a, int b)
{
//Checking the case divisor equals to 0
if (b == 0)
{
System.out.println("Error: divisor by zero
\n");
return -1;
}
// Checking for negative values
if (b < 0)
b = -b;
if (a < 0)
a = -a;
return(a-b*(a/b));
}
public static void main(String args[]) {
int a,b, result;
Scanner sc=new Scanner(System.in);
System.out.print("Please Enter a Dividend: ");
a=sc.nextInt();
System.out.print("Please Enter a Divisor: ");
b=sc.nextInt();
result= floorDivide(a,b);
System.out.print("The remainder is: "+result);
}
}
Output
user@user-Lenovo-V330-15IKB:~/JavaPrograms$ java Division
Please Enter a Dividend: 10
Please Enter a Divisor: 3
The remainder is: 1
user@user-Lenovo-V330-15IKB:~/JavaPrograms$ java Division
Please Enter a Dividend: -10
Please Enter a Divisor: 3
The remainder is: 1
user@user-Lenovo-V330-15IKB:~/JavaPrograms$ java Division
Please Enter a Dividend: 10
Please Enter a Divisor: -3
The remainder is: 1