gpt4 book ai didi

java - 质数和孪生代码出现奇怪的错误?

转载 作者:行者123 更新时间:2023-12-01 13:16:40 25 4
gpt4 key购买 nike

所以我正在做这个素数家庭作业,并给出了一个很好的例子,我想我已经记下了这部分的大部分内容。我遇到的一件事是“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 is an invalid type for the variable sieve

Syntax error on token "(", ; expected

Syntax error on token ")", ; expected

Syntax error on token "int", @ expected

Syntax error, insert "EnumBody" to complete BlockStatements

Syntax error, insert "enum Identifier" to complete EnumHeaderName

Syntax error on token "int", @ expected

我以前从未见过这样的事情?我不知道从哪里开始寻找解释?如果有人可以向我解释错误,我可能可以自己修复代码!

最佳答案

您正尝试在另一个方法中声明一个方法:

public static ArrayList<Integer> sieve (int maxValue)
{
public static void sieve (int n)
{

在 Java 中,这是不允许的,因此会出现错误。

您需要弄清楚您想要两个声明中的哪一个,并删除另一个(不要忘记删除右大括号)。

关于java - 质数和孪生代码出现奇怪的错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22415148/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com