[英]Calling method of another class JAVA
I'm using an external class that contains the method: public static boolean isPrime(int n).我正在使用包含以下方法的外部类:public static boolean isPrime(int n)。
I'm new in java and I don't know how to call a method from another class, I've been reading in other posts and they suggest to create an object, so that's what I did creating TestPrime objeto=new TestPrime();我是 Java 新手,我不知道如何从另一个类调用方法,我一直在阅读其他帖子,他们建议创建一个对象,这就是我创建 TestPrime objeto=new TestPrime() 所做的; but the if(objeto.isPrime(arrayInt[i])==true) isn't working.
但 if(objeto.isPrime(arrayInt[i])==true) 不起作用。
import com.utad.idcd.redes.PrimeNumber;
public class TestPrime {
public static void main(String[] args) {
TestPrime objeto = new TestPrime();
int arrayInt[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9 };
for (int i = 0; i < 9; i++) {
System.out.print("El" + arrayInt[i] + "es: ");
if (objeto.isPrime(arrayInt[i]) == true) {
System.out.print("primo\n");
} else {
System.out.print("no primo\n");
}
}
}
}
You have to create object of the PrimeNumber Class您必须创建 PrimeNumber 类的对象
import com.utad.idcd.redes.PrimeNumber;
public class TestPrime {
public static void main(String[] args) {
int arrayInt[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9 };
for (int i = 0; i < 9; i++) {
System.out.print("El" + arrayInt[i] + "es: ");
if (PrimeNumber.isPrime(arrayInt[i]) == true) {
System.out.print("primo\n");
} else {
System.out.print("no primo\n");
}
}
}
}
Now it should run fine.现在它应该运行良好。
Edit: sorry, I did not see the method was static;编辑:抱歉,我没有看到该方法是静态的; since your method is static and public you can also use static import like:
由于您的方法是静态和公共的,您还可以使用静态导入,例如:
import static com.utad.idcd.redes.PrimeNumber.isPrime;
and then directly use the function as然后直接使用该函数作为
if (isPrime(arrayInt[i]) == true) {
Please look the example below guy,请看下面的例子,伙计,
class PrimeNumber{类素数{
public void boolean isPrimeNumber(){ public void boolean isPrimeNumber(){
//Your code check the prime number here //您的代码在这里检查质数
} }
} }
class MainTest {类 MainTest {
public static void main(String[] args) {
PrimeNumber obj =new PrimeNumber();
int arrayInt[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9 };
for(int i=0; i<9; i++){
System.out.print("El" + arrayInt[i] + "es: ");
if(obj.isPrimeNumber(arrayInt[i])==true){
System.out.print("primo\n");
}
else {
System.out.print("no primo\n");
}
}
}
} }
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.