2013-03-28 49 views
0

試圖瞭解爲什麼我的程序過早終止。運行加侖升轉換方法好,但在那裏停止。不運行「根」方法(其目的是計算1到100的平方根)。我相信這更像格式化問題而不是語義。謝謝你的幫助。之前程序終止的原因

package gallons.to.liters; 

public class converter {      
public static void main(String args[]) {  
    double gallons;       
    double liters;   

    gallons = 10; 
    liters = gallons * 3.7854; 

    System.out.println("The number of liters in " + gallons + " gallons is " + 
      liters); 
    System.out.println(); 

} 


public static void root(String args[]) { 
    double counter; 
    double square; 

    square = 0; 
    counter = 0; 

    for(square = 0; square <= 100; square++); 
     square = Math.sqrt(square); 
     counter++; 
     System.out.println("The square root of " + counter + " is " + 
        square); 



}  
} 
+0

'root'不應該被調用,除非你明確地去做,例如,通過'main'中的'root(args)'''行。 JVM只調用你的'main'。 –

回答

1

你永遠不呼叫root方法。添加到主要:

public static void main(String args[]) {  
    double gallons;       
    double liters;   

    gallons = 10; 
    liters = gallons * 3.7854; 

    System.out.println("The number of liters in " + gallons + " gallons is " + 
      liters); 
    System.out.println(); 

    root(args); // ADD to call the method. 
} 
0

只有JVM調用public static void main(String args[])作爲java程序的入口點。

實際上您從來不會在main方法中調用root方法。調用此方法執行root方法的語句。

這樣的電話。

public static void main(String args[]) 
{ 
    ........ 
    root(); 
} 

我發現沒有使用你在root方法中傳遞的參數。所以刪除它。

for(square = 0; square <= 100; square++); 

在for循環結束時刪除分號。

public static void root() { 
    double counter = 0; 
    for(counter= 0; counter <= 100; counter++) { 
     System.out.println("The square root of " + counter + " is " + Math.sqrt(counter)); 
    } 
} 
+0

@Fluxcapacitor如果解決了您的問題,請接受答案。 –

0

你必須添加一個調用到

root(args) 

,並出現了一些問題,你的方法,我已經解決了,請在下面找到

public static void root(String args[]) 
    { 
     double counter; 
     double square; 

     square = 0; 
     counter = 0; 

     for (counter = 0; counter <= 100; counter++) 
     { 
      square = Math.sqrt(counter); 
      System.out.println("The square root of " + counter + " is " + square); 
     } 

    } 
0

附加線root(args);修改版這會調用你的方法。

無論有什麼主要方法將被調用,直到main方法結束。 Java不會像人類一樣從頭到尾運行.java文件。它僅調用主方法中存在的那些行。包含行的主要方法可以根據編程規則調用靜態或非靜態的其他方法。理解所有這些概念的最好方法是學習OOP。購買兩本「Head First core java」的書,一本給你,另一本給你的朋友討論。

public static void main(String args[]) { 
     double gallons; 
     double liters; 

     gallons = 10; 
     liters = gallons * 3.7854; 

     System.out.println("The number of liters in " + gallons + " gallons is " + liters); 
     System.out.println(); 
     root(args); //call this method here as per your expection of the output 

    } 
相關問題