public class Prime { public static void main(String[] args) { Scanner in = new Scanner(System.in); int x = in.nextInt(); System.out.println(isPrime(x)); } public boolean isPrime(int n) { for (int i = 2; i <= Math.sqrt(n); i++ ) { if (n % i == 0){ return false;// Write your solution here } } return true; } }为什么这段代码会报错
时间: 2023-06-15 13:08:30 浏览: 92
这段代码会报错是因为`isPrime`方法是静态方法,而静态方法无法调用非静态方法。解决方法有两种:
1. 将`isPrime`方法也设置为静态方法:
```
public static boolean isPrime(int n) {
for (int i = 2; i <= Math.sqrt(n); i++ ) {
if (n % i == 0){
return false;
}
}
return true;
}
```
2. 创建一个`Prime`类的对象,然后调用`isPrime`方法:
```
public class Prime {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int x = in.nextInt();
Prime prime = new Prime();
System.out.println(prime.isPrime(x));
}
public boolean isPrime(int n) {
for (int i = 2; i <= Math.sqrt(n); i++ ) {
if (n % i == 0){
return false;
}
}
return true;
}
}
```
阅读全文