【问题标题】:I am having trouble printing out an instance method and a class method我无法打印出实例方法和类方法
【发布时间】:2017-11-19 18:30:22
【问题描述】:

所以我正在使用的代码应该检查一个数字是否是素数,然后我需要打印出它是否是素数的结果?从我的实例和类方法。我遇到了麻烦,因为我觉得我设置了一切正确,但是当我运行程序时我没有得到任何结果。我会接受任何建议。放轻松,这是我编程的第一年。

import java.io.IOException;
import java.util.Scanner;

public class Assignment4 {
    public static void main(String[] args) throws IOException {

        Scanner myInput = new Scanner(System.in);
        int someValue = myInput.nextInt();

        MyInteger myInt = new MyInteger(someValue);
        System.out.println("Testing instance method:");
        System.out.println(myInt.isPrime());
        System.out.println("Testing class method:");
        System.out.println(MyInteger.isPrime(myInt));
    }
}

class MyInteger {
    private int value;

    public MyInteger(int value) {
        this.value = value;
    }
    public int getValue() {
        return value;
    }
    public boolean isPrime() {
        int sqrt = (int) Math.sqrt((double)value);
        for(int i = 2; i <= sqrt; i++) {
            if (value % i == 0) return false;
        }
        return true;
    }

    public static boolean isPrime(MyInteger myInt) {
        return myInt.isPrime();
    }
}

【问题讨论】:

  • “没有结果”是什么意思?什么都没有打印?请显示您在运行程序时实际看到的内容。
  • 请阅读minimal reproducible example并相应地完善您的问题。
  • @GhostCat:实际上,这一个有效的 MCVE。我相应地对这个问题进行了投票,并鼓励你也这样做。我猜他做错了。
  • 程序没问题,一旦你输入一个数字并回车,结果就在那里。
  • public static boolean isPrime(MyInteger myInt) {return myInt.isPrime();} 没有意义,因为我们可以简单地写成myInt.isPrime(); 而不是MyInteger.isPrime(myInt)。该方法可能应该以int 而不是MyInteger 作为参数,然后将其包装在MyInteger 中并返回其isPrime 的结果,如return new isPrime(intValue).isPrime();

标签: java methods instance class-method


【解决方案1】:

程序运行良好,一切都很好,我认为您没有为程序提供输入。

运行程序,在屏幕/控制台上写任意数字,回车,就会看到输出。

这是工作截图:

【讨论】:

    【解决方案2】:

    您的类方法对您编写它的方式没有任何好处。

    您必须传递 int 而不是 MyInteger

    像这样:

    public static boolean isPrime(int integer) {
        MyInteger myInt = new MyInteger(integer);
        return myInt.isPrime();
    } 
    

    而且你的代码也在工作

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-06-12
      • 1970-01-01
      • 2021-06-03
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多