Search code examples
javaif-statementswitch-statementquadraticdeterminants

How can I change this if-statement to switch?


//is the following code about quadratic formulas convertible to switch method?

Public class blah blah
  Public static void main(String[] args) {
    System.out.println("enter letter a");
    New Scanner= System.in
    Int a = input.nextint()

//same thing repeated for letters b and c.

//int d is for discriminant.

    Int d= math.pow(b^2 -4ac, 0.5);
    Int r1= (-(b) - (d))/2(a)
    Int r2= (-(b) + (d))/2(a)

    If(d>0){
      System.out.println("2 solutions: r1; " + r1+ " and r2" + r2);
    }else if(d=0){
      System.out.println("1 solutions: r1; " + r1+ " and r2" + r2);
    }else{
      System.out.println("no real solution");
}

Solution

  • If you really really really wanna use a switch case

    private static void switchOnIntegerPolarity() {
            int a = 1;
            int b = 2;
            int c = 3;
            int d = (int) Math.pow(b ^ 2 - 4 * a * c, 0.5);
            int r1 = (-(b) - (d)) / 2 * (a);
            int r2 = (-(b) + (d)) / 2 * (a);
    
            switch ((int) Math.signum(d)) {
            case 0: // Zero
                System.out.println("1 solutions: r1; " + r1 + " and r2" + r2);
                break;
            case 1: // 'd' is Positive
                System.out.println("2 solutions: r1; " + r1 + " and r2" + r2);
                break;
            case -1: // 'd' is Negative
                System.out.println("no real solution");
                break;
            }
        }