[英]Java - Sum of prime numbers of random-generated array-values
I am a beginner in Java and I have a task to do, to calculate the sum of prime numbers from the random-generated values of an array. 我是Java的初学者,我有一个任务要做,即根据数组的随机生成的值计算素数的总和。
So, I was told that I should have 3 classes: 因此,我被告知我应该参加3节课:
1) MyArray - where I have already written this code: 1)MyArray-我已经在其中编写了以下代码:
...
public int[] createArray(int n) {
int[] a = new int[n];
for (int i = 0; i < a.length; i++) {
a[i] = rnd.nextInt(10);
}
return a;
}
...
2) IsPrime - where I should do the checking if a number is a prime or not. 2)IsPrime-在这里我应该检查数字是否为质数。 The problem is I don't know how to 'connect' the array from MyArray to the IsPrime class.
问题是我不知道如何将数组从MyArray“连接”到IsPrime类。 I started with a boolean method checkPrime, that has an object m from the MyArray class as a parameter, but I don't know how to continue, how to access the array from the IsPrime class.
我从布尔方法checkPrime开始,该方法具有MyArray类的对象m作为参数,但是我不知道如何继续以及如何从IsPrime类访问数组。
I am thankful for any given opinions and advice. 感谢您提出的任何意见和建议。 Thank you!
谢谢!
PS My third class Run.java has the main-method. PS我的第三类Run.java具有主要方法。
It should basically look like that: 它基本上应该看起来像这样:
MyArray myArray = new MyArray();
IsPrime isPrime = new IsPrime();
int sum = 0;
for(int num : myArray.createArray(20)){
if(isPrime.checkPrime(num)){
sum += num;
}
}
System.out.println(sum);
Put it into your main method in Run class 将其放入Run类的主方法中
You can call IsPrime method from Run Class like below 您可以从Run Class调用IsPrime方法,如下所示
Class Run {
public static void main(String[] args]) {
IsPrime ip=new IsPrime();
int sum= ip.checkPrime();
System.out.print(sum);
}
}
Class IsPrime {
public int checkPrime(int length){ MyArray m=
MyArray (); int[] arr = m.createArray(5);
//iterating arr and call to isPrime() method
}
public boolean isPrime(int num){
// prime checking logic
}
}
You should declare in the class where you have the array. 您应该在类中声明您拥有数组的位置。 In the class isPrime, you should declare a method that sums all the prime number, received in the parameter int[].
在isPrime类中,您应该声明一个方法,该方法将参数int []中接收的所有素数相加。 Just as an idea, and to be quicker, you can use ForkJoinPool to create multiple Threads, but I think that is not your main target for the moment.
作为一个想法,并且为了更快起见,您可以使用ForkJoinPool创建多个线程,但是我认为这不是当前的主要目标。
public class YourClass{
private int[] MyArray;
//Constructor
//Methods
//Getter of MyArray
public int[] getMyArray(){
return this.MyArray;
}
};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.