【发布时间】: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