I'm trying to not have the user input be 0 for "a" since this would cause the equation to divide by zero, which outputs an error, i would to be able to have a println saying that you cannot divide by zero if the user inputs 0 for "a" Here is my code, I'm not sure what I'm doing wrong, I'm still new at this, just need help:
import java.util.Scanner;
class a3main{
public static void main(String[] args){
Scanner keyboard = new Scanner(System.in);
System.out.println("Enter the value of a");
int a = keyboard.nextInt();
System.out.println("Enter the value of b");
int b = keyboard.nextInt();
System.out.println("Enter the value of c");
int c = keyboard.nextInt();
double R1, R2, dis;
dis = b * b - 4 * a * c; // This is the discriminant formula
if(dis > 0 )
{
System.out.println("The roots are both real numbers and unequal");
R1 = (-b + Math.sqrt(dis))/(2*a);
System.out.println("The first root is: " + R1);
R2 = (-b - Math.sqrt(dis))/(2*a);
System.out.println("The second root is: " + R2);
}
else if(dis == 0)
{
System.out.println("The roots are both equal and are equal");
R1 = (-b + Math.sqrt(dis))/(2*a);
System.out.println("The root is: " + R1);
}
else if (a == 0)
{
System.out.println("You cannot divide by 0");
}
else
{
System.out.println("The roots are imaginary");
}
}
}
You need to put your if(a == 0)
check before your checks that look at dis.