【问题标题】:Why does my Java code not execute System.out.println? [closed]为什么我的 Java 代码不执行 System.out.println? [关闭]
【发布时间】:2014-01-28 17:27:10
【问题描述】:

我正在使用 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;
    }
}

【问题讨论】:

  • ...因为你从不打电话给checkFermat?
  • 我不同意反对意见。如果发布者(显然)正在学习 Java,那么这是一个非常合理的问题。仅仅因为答案对有经验的程序员来说是显而易见的,并不意味着它对初学者来说是显而易见的。

标签: java main


【解决方案1】:

您永远不会从main 调用checkFermat 函数。在 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 不会自动应用于函数。您必须将它们作为参数显式传递。注意main 中的abcn 变量与@9876543 中的abcn 完全分开:3它们是单独的变量,因为它们是在单独的函数中声明的。

【讨论】:

  • 非常感谢,没有你们我不知道该怎么办。 :)
【解决方案2】:

因为你没有在main中调用checkFermat方法

试试,

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

 }

【讨论】:

    【解决方案3】:

    更新主方法:

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

    【讨论】:

      【解决方案4】:

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

      【讨论】:

        【解决方案5】:

        你只需像下面这样调用方法 checkFermat

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

        练习 e = 新练习(); e.checkFermat(a,b,c,n);

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2023-01-13
          • 2019-01-05
          • 1970-01-01
          • 2013-08-27
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多