if语句检查不起作用

时间:2018-02-11 18:00:34

标签: java if-statement

每当我为第一个int运行带有负数的代码时,它就会继续运行代码,即使我有一个if语句来检查它。

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");
    }
}

1 个答案:

答案 0 :(得分:0)

注意:

由于您的空else语句,您获得不受欢迎的输出的原因是 NOT 。相反,您未能为您的代码提供所需的必要方向。我们想象一下,我运行了这段代码,并将-6作为a输入。显然,我得到以下错误:

  

错误:&#34; +&#34;&#39;一个&#39;&#34; +&#34;不能少于1

.....但是,代码仍然从那里继续执行并运行程序的剩余部分。

我提供的一个好方法是使用do-while循环。使用do-while循环,您可以继续提示用户输入a是否小于或等于零。研究下面的代码说明,以更好的方式接受您的输入:

    do{
        System.out.println("Enter a: ");
        a = s.nextInt();
        if(a <= 0) {
            System.out.println("Error: " +"'a'" +" cannot be less than 1");
            }
        }

    while(a <= 0);

    System.out.println("Enter b: ");
    b = s.nextInt();
    System.out.println("Enter c: ");
    c = s.nextInt();

这样,如果a&lt; = 0,将始终提示用户输入a的值。

我希望这有帮助..快乐编码!