2015-12-07 87 views
-1

我正在嘗試創建一個程序,計算並打印給定方程的實際解決方案數量。 用戶輸入A,B和C的值。 如果用戶輸入A = 0的值並且不繼續詢問其他值,我希望程序退出。當IF語句== true時退出程序?

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

'return'?你必須顯示這個代碼是_where_。它是在一個函數中嗎?控制流程有多種方式。 – Arc676

+2

'if(coA == 0){System.exit();基本上?這就引出了爲什麼你告訴用戶0不可接受的問題,如果你想用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 "); 
} 
+0

感謝您的回答,工作:) –

+0

我會將它標記爲10分鐘後回答 –