所以我正在完成这个Prime Numbers的家庭作业,给出了一个很好的例子,我认为我已经完成了大部分的工作。我挣扎的一件事就是说明了#34; public static void sieve(int n)"也发生在" private static int twinPrime()"
以下是代码:
import java.util.*;
public class PrimeNumbers
{
public static void main (String [] args)
{
Scanner in = new Scanner(System.in);
System.out.print("Enter a value for n: ");
int n = in.nextInt();
in.nextLine(); // clear input buffer
System.out.println();
// Generate a list of prime numbers between 2 and n
// to test Part 1
ArrayList<Integer> primes = sieve(n);
System.out.println("Prime numbers between 2 and " + n + ":\n");
System.out.println(primes);
System.out.println();
// Test Part 2
System.out.println("The twin primes less than " + n + " are:\n");
twins(n);
System.out.println();
}
// COMPLETE THIS METHOD FOR PART 1
public static ArrayList<Integer> sieve (int maxValue)
{
public static void sieve (int n)
{
// 1 = assumed prime, 0 = known not prime
// Create a list of numbers from 0-n
ArrayList<Integer> sieve =
new ArrayList<Integer>(n+1);
// Fill initial sieve with non-zeros (assumed prime)
int index;
for (index = 0; index <= n; index++)
{
sieve.add(index);
}
System.out.println("Starting sieve: " + sieve);
// For each position/value >= 2, if it's 1,
// cross off its later multiples (set them to 0)
for (index = 2; index < sieve.size(); index++)
{
if (sieve.get(index) > 0)
{
System.out.println(index + " is prime");
// Mark off multiples of index
int mult = 2 * index; // first multiple
for (; mult < (n+1); mult += index)
{
// Increment by (index) each time
// set() takes position, new value
sieve.set(mult, 0); // mark off value
}
System.out.println(sieve);
}
}
// Remove all non-prime values
sieve.remove(0);
sieve.remove(0);
for (index = 0; index < sieve.size(); index++)
{
if (sieve.get(index) == 0)
{
sieve.remove(index);
index--;
}
}
System.out.println(sieve);
}}
// COMPLETE THIS METHOD FOR PART 2
public static void twins (int max)
{
// ADD YOUR CODE HERE
}
}
以下是错误:
void是变量筛的无效类型
令牌上的语法错误&#34;(&#34; ,;预期
令牌上的语法错误&#34;)&#34;,;预期
和
令牌上的语法错误&#34; int&#34;,@ expected
语法错误,插入&#34; EnumBody&#34;完成BlockStatements
语法错误,插入&#34;枚举标识符&#34;完成EnumHeaderName
令牌上的语法错误&#34; int&#34;,@ expected
我以前从未见过这样的事情?而且我不知道从哪里开始寻找解释?如果有人可以向我解释错误,我可以自己修复代码!
答案 0 :(得分:1)
您正在尝试在另一个方法中声明一个方法:
public static ArrayList<Integer> sieve (int maxValue)
{
public static void sieve (int n)
{
在Java中,这是不允许的,因此是错误。
你需要找出你想要的两个声明中的哪一个,并摆脱另一个声明(不要忘记删除结束的大括号)。