dimanche 11 février 2018

java if statement check not working

Whenever I run this code with a negative number for the first int it keeps running the code even though I have an if statement that checks for this.

import java.util.Scanner;
public static void main(String[] args) {
    int a,b,c;
    double r1, r2, d;
    Scanner s = new Scanner(System.in);
    System.out.println("Enter the coefficients of the equation: ");
    System.out.println("Enter a: ");
    a = s.nextInt();
    System.out.println("Enter b: ");
    b = s.nextInt();
    System.out.println("Enter c: ");
    c = s.nextInt();
    if(a <= 0) {
        System.out.println("Error: " +"'a'" +" cannot be less than 1");
    }
    else {

    }
    System.out.println("Given dquadratic equation:" + a + "x^2 + " + b + "x + " + c + ",");
    d = b * b - 4 * a * c;
    if(d > 0) {
        System.out.println("Roots are real and unequal");
        r1 = (-b + Math.sqrt(d)/(2*a));
        r2 = (-b + Math.sqrt(d)/(2*a));
        System.out.println("Root 1: " + r1);
        System.out.println("Root 2: " + r2);
    }
    else if(d == 0){
        System.out.println("Roots are real and equal");
        r1 = (-b + Math.sqrt(d)/(2*a));
        System.out.println("Root 1: " + r1);
    }
    else {
        System.out.println("Roots are imaginary");
    }
}

}

Aucun commentaire:

Enregistrer un commentaire