为什么我的Java代码不执行System.out.println?

时间:2014-01-28 17:27:10

标签: java main

我正在使用Netbeans IDE,但它没有检测到任何错误。我只是好奇为什么这段代码没有执行。仅供参考,这是“思考Java:如何像计算机科学家一样思考”的练习4.4。

import java.lang.Math;
public class Exercise {
    public static void checkFermat(int a, int b, int c, int n){

        if ((Math.pow(a, n))+(Math.pow(b, n))==(Math.pow(c, n)) && n!=2){
            System.out.println("Holy smokes, Fermat was wrong!");
        }
        else{
            System.out.println("No, why would that work?");
        }
    }

    public static void main(String args[]){
        int a = 8;
        int b = 4;
        int c = 10;
        int n = 3;
    }
}

5 个答案:

答案 0 :(得分:8)

您永远不会从checkFermat拨打main功能。在Java程序中执行的唯一代码是main内的代码。您定义的任何其他方法仅在从main中调用时才会执行。因此,您的代码应为:

import java.lang.Math;

public class Exercise {
    public static void checkFermat(int a, int b, int c, int n){

        if ((Math.pow(a, n))+(Math.pow(b, n))==(Math.pow(c, n)) && n!=2){
            System.out.println("Holy smokes, Fermat was wrong!");
        }
        else{
            System.out.println("No, why would that work?");
        }
    }

    public static void main(String args[]){
        int a = 8;
        int b = 4;
        int c = 10;
        int n = 3;

        checkFermat(a, b, c, n); //call the method here
    }
}

此外,您的本地变量abcn不会自动应用于该功能。您必须明确地将它们作为参数传递。请注意a内的bcnmain变量与a完全分开,b c中的ncheckFermat:它们是单独的变量,因为它们是在单独的函数中声明的。

答案 1 :(得分:2)

因为您没有在主

中调用checkFermat方法

尝试,

public static void main(String args[]){
        int a = 8;
        int b = 4;
        int c = 10;
        int n = 3;
        checkFermat(a,b,c,n);

 }

答案 2 :(得分:2)

更新主要方法:

public static void main(String args[]){
        int a = 8;
        int b = 4;
        int c = 10;
        int n = 3;
        Exercise.checkFermet(a,b,c,n);
    }

答案 3 :(得分:0)

要执行 System.out.println()语句,您需要调用 checkFermat 函数而不调用它,它将永远不会执行该语句但是当您调用它时main函数将调用 checkformat 并执行该函数内部编写的代码...

答案 4 :(得分:0)

您只需将方法checkFermat称为bellow

即可

Exercise.checkFermat(a,b,c,n)或

练习e =新练习(); e.checkFermat(A,B,C,N);

相关问题