IF语句== true时退出程序?

时间:2015-12-07 15:53:33

标签: java netbeans

我试图创建一个程序来计算和打印给定方程的真实解决方案的数量。 用户输入A,B和C的值。 如果用户输入A = 0的值而不是继续询问其他值,我希望程序退出。

public static void main(String[] args) {

    Scanner s = new Scanner(System.in);
    System.out.println("Enter a vlaue for A : ");
    int coA = s.nextInt();

    if (coA==0){
        System.out.println("Error ! Enter a vlaue larger than 0 ");
    };
    System.out.println("Enter a vlaue for B : ");
    int coB = s.nextInt();

    System.out.println("Enter a vlaue for C : ");
    int coC = s.nextInt();

    double coTotal = (Math.pow(coB, 2))-4*coA*coC;

    if(coTotal>0){
        System.out.println(" The System has two solutions ");
    }
    if (coTotal==0){
        System.out.println(" The System has one solutions ");
    }
    if(coTotal<0){
        System.out.println(" The System has ZERO solutions ");
    } 
}

1 个答案:

答案 0 :(得分:2)

如果此代码在main中,您可以使用System.exit,就像这样。我使用-1表示输入存在问题。您可以使用其他错误代码:

Scanner s = new Scanner(System.in);
System.out.println("Enter a vlaue for A : ");
int coA = s.nextInt();

if (coA==0){
    System.out.println("Error ! Enter a vlaue larger than 0 ");
    System.exit(-1);
};
System.out.println("Enter a vlaue for B : ");
int coB = s.nextInt();

System.out.println("Enter a vlaue for C : ");
int coC = s.nextInt();

double coTotal = (Math.pow(coB, 2))-4*coA*coC;

if(coTotal>0){
    System.out.println(" The System has two solutions ");
}
if (coTotal==0){
    System.out.println(" The System has one solutions ");
}
if(coTotal<0){
    System.out.println(" The System has ZERO solutions ");
}