【发布时间】:2014-05-06 07:46:06
【问题描述】:
下面显示的PrimeDetector 类具有描述每种方法用途的文档。测试器类创建PrimeDetector 类的对象,并尝试从hasPrime() 方法返回的ArrayList 中打印一组生成的整数值。我没有看到我的错误,因为我创建了一个可以正常工作的程序版本。它只打印前 3 个素数,并返回只检测到 3 个素数——这让我相信问题出在 PrimeDetector 类中,在 for 循环中的某处,尽管我不能确定,因为它与我的程序版本的结构几乎相同——据我所知。我将包括单个过程类,以及 OOP 版本及其测试器。
/**
* The PrimeDetector class detects prime numbers within a user's
* given set [0,n] where n is a user-given upper limit.
*
* @author A. Mackey
* @version 06/05/14
*/
import java.util.*;
public class PrimeDetector {
private int n;
private int primeCounter;
private ArrayList<Integer> primeList = new ArrayList<Integer>();
/**
* Constructor for objects of class PrimeDetector
* @param n is the upper limit in the set [0,n] tested with the hasPrime() method.
*/
public PrimeDetector(int n) {
this.n = n;
}
/**
* @return an ArrayList of type Integer containing all prime values within the set [0,n].
*/
public ArrayList<Integer> hasPrime() {
primeCounter = 0;
for (int i = 1; i <= n; i++) {
boolean isPrime = true;
for (int j = 2; j <= i / 2; j++) {
if (i % j == 0) {
isPrime = false;
break;
}
}
if (isPrime) {
primeCounter++;
primeList.add(i);
} else {
break;
}
}
return primeList;
}
/**
* @return primeCounter variable which holds and integer value equivalent to the number of prime values in
* the [0,n] set evaluated in the hasPrime() method.
*/
public int getPrimeCounter() {
return primeCounter;
}
}
测试人员:
/**
* The PrimeDetectorTest class tests the PrimeDetector class, which detects prime numbers within a user's
* given set [0,n] where n = a user-given upper limit.
*
* @author A. Mackey
* @version 06/05/14
*/
import java.util.*;
public class PrimeDetectorTest
{
public static void main(String [] args)
{
Scanner in = new Scanner(System.in);
System.out.print("Enter a positive integer you wish to find primes up to: ");
int n = in.nextInt();
System.out.println("The following list is prime within the range [0, " + n + "]: ");
PrimeDetector list = new PrimeDetector(n);
ArrayList<Integer> primeList = list.hasPrime();
for (int s : primeList)
{
System.out.println(s + " is prime.");
}
System.out.println(list.getPrimeCounter() + " prime numbers within this set.");
}
}
程序版本:
import java.util.*;
public class PrimeDetectorV1
{
public static void main(String [] args)
{
Scanner in = new Scanner(System.in);
System.out.print("Enter a positive integer you wish to find primes up to: ");
int n = in.nextInt();
int primeCounter = 0;
System.out.println("The following list is prime within the range [0, " + n + "]: ");
for(int i = 0; i <= n; i++)
{
while (i>0)
{
boolean isPrime = true;
for (int j = 2; j <= i/2; j++)
{
if(i % j == 0)
{
isPrime = false;
break;
}
}
if (isPrime)
{
System.out.println(i + " is prime.");
primeCounter++;
break;
}
else
{
break;
}
}
}
System.out.println("There are " + primeCounter + " prime numbers within this set.");
}
}
【问题讨论】:
标签: java oop for-loop logic output