I am trying to write a program that will take two user input numbers and then perform calculations based off of them, but I want to use if-statements to check if it is trying to divide by zero or the output will be infinity.
import java.util.Scanner;
public class work {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
double a, b, c, d;
System.out.printf("Enter the first number:");
a = scan.nextDouble();
System.out.printf("Enter the second number:");
b = scan.nextDouble();
/* various calculations */
c = a / b;
d = b / a;
if (a > 0)
{
System.out.printf("a/b = %.2f\n", c);
}
if (b > 0)
{ System.out.printf("b/a = %.2f\n", d);
}
else if (a <= 0)
{ System.out.printf("a/b = %.1f\n", d);
if (b > 0)
System.out.printf("a/b = INF\n");
}
}
}
So for example if I input 4 and 5 it will end up like this:
Enter the first number: 4
Enter the second number: 5
a/b = 0.80
b/a = 1.25
However I am having trouble getting it to check for zero, and end up with lots of weird outputs. How can I get outputs like this?
------ Sample run 2:
Enter the first number: 0
Enter the second number: 4
a/b = 0.0
b/a = INF
------ Sample run 3:
Enter the first number: 4
Enter the second number: 0
a/b = INF
b/a = 0.0
------ Sample run 4:
Enter the first number: 0
Enter the second number: 0
a/b = INF
b/a = INF