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

som*_*ane 3 java program-entry-point

我正在使用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;
    }
}
Run Code Online (Sandbox Code Playgroud)

App*_*ish 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
    }
}
Run Code Online (Sandbox Code Playgroud)

此外,你的局部变量a,b,c,并且n不会自动应用到的功能.您必须明确地将它们作为参数传递.请注意a,b,c,和n变量的内部main是由完全独立的a,b,c,和ncheckFermat:它们是独立的变量,因为它们是独立的函数声明.