0

试图了解为什么我的程序过早终止。运行加仑到升的转换方法可以,但停在那里。不运行“root”方法(其目的是计算数字 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);



}       
}
4

4 回答 4

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.
}
于 2013-03-28T15:27:34.777 回答
0

JVM 调用仅public static void main(String args[])作为 java 程序的入口点。

实际上,您永远不会root在方法内部调用main方法。调用该方法执行方法的语句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));
    }
} 
于 2013-03-28T15:31:26.890 回答
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 );
        }

    }
于 2013-03-28T15:33:00.323 回答
0

添加root(args);将调用您的方法的行。

无论有什么 main 方法,都会调用到 main 方法结束。Java 不像人类从头到尾读取那样运行 .java 文件。它仅调用 main 方法中存在的那些行。包含行的主方法可以根据编程规则调用静态或非静态的其他方法。理解所有这些概念的最好方法是学习 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

    }
于 2013-03-28T15:33:11.137 回答