【发布时间】:2018-10-17 23:05:51
【问题描述】:
所以我需要帮助弄清楚为什么我的代码不包括数字 2,而它在主要打印行上包括数字 99。我需要更改我的 findPrime() 上的某些内容吗?我尝试使用索引,但变得更糟。
class Sieve {
private int max;
private boolean[] numbers;
public Sieve(int max) {
if (max < 2) {
throw new IllegalArgumentException();
}
this.max = max;
numbers = new boolean[max];
numbers[0] = false;
numbers[1] = false;
numbers[2] = true;
for (int i = 2; i < max-1; i++) {
numbers[i] = true;
}
}
public void findPrimes() {
for (int num = 2; num < max-1; num++) {
int multiples = num + num;
while (multiples < max-1) {
numbers[multiples-1] = false;
multiples += num;
}
}
}
@Override
public String toString() {
StringBuilder builder = new StringBuilder();
for (int num = 2; num < max; num++) {
if (numbers[num]) {
builder.append(num+1).append(" ");
}
}
return builder.toString();
}
}
class Driver
{
// MAIN. Find some primes.
public static void main(String [] args)
{
Sieve sieve = null; // We must initialize SIEVE or Java will cry.
// 5 points. This must print "Sieve size must be at least 2." but without the
// quotes.
try
{
sieve = new Sieve(0);
}
catch (IllegalArgumentException oops)
{
System.out.println("Sieve size must be at least 2.");
}
// 5 points. This must print nothing.
try
{
sieve = new Sieve(100);
}
catch (IllegalArgumentException oops)
{
System.out.println("Sieve size must be at least 2.");
}
// 10 points. This must print integers from 2 to 99, separated by blanks.
System.out.println(sieve);
// 10 points. This must print the prime numbers between 2 and 99, separated by
// blanks. They are:
//
// 2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71 73 79 83 89 97
sieve.findPrimes();
System.out.println(sieve);
}
}
它显示的是这个,而不是在程序的开头有数字 2 并且在程序的最后一行没有数字 99。
Sieve size must be at least 2.
3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99
3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71 73 79 83 89 97 99
【问题讨论】:
-
也请查看How to debug small programs。它不会解决您的直接问题,但会为您提供可以遵循的步骤,这些步骤应该可以帮助您自己解决问题,或者即使这不成功,也至少可以帮助您更好地隔离您的问题,以便您的问题可以更专注,更容易回答。
-
这是因为你说
2不是这条线的素数:numbers[1] = false;。您需要决定是直接按数字索引数组,还是按number - 1。现在你在不同的地方做这两个,这自然会导致错误。 -
我删除了那行代码,仍然给我同样的输出。
-
“给你错误的输出”与“错误”有何不同?错误不仅仅是“编译器错误”,它是“它没有按照指定的方式执行”
标签: java