所以我有一个任务,我们必须使用Sieve of Eratosthenes算法生成0之间的所有素数,用户确定的值小于200,然后将这些素数写入一个名为“primesTo200.txt”的文件中,最大值每行10个素数。现在,当我输入120作为最大素数值时,我的代码工作得很好,但是当我尝试输入0到200之间的任何其他数字时,它会生成素数很好但是当它尝试时我得到一个“越界异常”错误写入文件。这是为什么??我没有硬编码任何只会使120个工作的东西......有人可以帮助我吗? ^ _ ^
import java.util.Arrays;
import java.util.Scanner;
import java.io.*;
public class A1Q1
{
public static void main(String[] args)
{
Scanner keyboard = new Scanner(System.in);
System.out.println("Enter a maximum value up to which you wish to generate prime numbers [max 200]: ");
int maxValue = keyboard.nextInt();
while(maxValue > 200 || maxValue < 0)
{
System.out.println("Sorry, that is not a max value between [0 - 200]. Please enter another integer: ");
maxValue = keyboard.nextInt();
}
int[] primes = generatePrimes(maxValue);
System.out.println(Arrays.toString(primes));
try
{
FileWriter fileName = new FileWriter("primesTo200.txt.");
recordArray(primes, fileName);
}
catch(IOException ioe)
{
ioe.printStackTrace();
}
}
public static int[] generatePrimes(int maxValue)
{
boolean[] array = new boolean[maxValue + 1];
int[] primesFull = new int[maxValue];
int count = 0;
for(int i = 2; i < array.length; i++)
{
array[i] = true;
}
for(int nextPrime = 2; nextPrime * nextPrime <= maxValue; nextPrime++)
{
for(int i = 2; i * nextPrime <= maxValue; i++)
{
array[i * nextPrime] = false;
}
}
for(int i = 2; i <= maxValue; i++)
{
if(array[i] == true)
{
primesFull[count] = i;
count++;
}
}
int[] primes = new int[count];
System.arraycopy(primesFull, 0, primes, 0, count);
return primes;
}
public static void recordArray(int[] primes, FileWriter fileName)
{
PrintWriter fileOut = new PrintWriter(fileName);
int lineLength = 10;
int count = 0;
while(count < primes.length)
{
for(int i = 0; i < lineLength; i++)
{
fileOut.print(primes[count] + " ");
count++;
}
fileOut.print("\n");
}
fileOut.close();
System.out.println("Program wrote to the file successfully.");
}
}
答案 0 :(得分:2)
for(int i = 0; i < lineLength; i++)
就是问题所在。
每次你的外循环迭代(并跳过count < primes.length
的检查)时,你将经历10个素数,无论你是否有10个素数留在你的文件中