这是我的程序,用于计算92之前的质数。它的工作原理像一个超级按钮。我希望将输出放入名为VectorDump的新文件中,而不是仅显示在常规屏幕上。我在这里的程序中从哪里开始?下面是我的代码,我的代码输出在页面底部。
这是我得到的输出
92之前的素数是:
2 3 5 7 11 13 17 19 23 29
31 37 41 43 47 53 59 61 67 71
73 79 83 89
import java.util.*;
public class PrimeByVector
{
public static void main(String[] args)
{
final int NUMBER_PER_LINE = 10;
int count = 0;
// java.util.Vector vector = new java.util.Vector();
Vector vector = new Vector();
System.out.println("The primes before 92 are: \n");
for (int n = 2; n < 92; n++)
PrintWriter writer = null;
try{
writer = new PrintWriter("VectorDump", "UTF-8");
} catch (Exception e) {
break;
}
Iterator it = vector.iterator();
while(it.hasNext())
{
writer.print(
it.next() + " "
);
}
writer.close();
{
boolean isPrime = true;
for (int i = 0; i < vector.size(); i++)
{
int primeNumber =
((Integer)(vector.elementAt(i))).intValue();
if (primeNumber > Math.sqrt(n)) break;
if (n % primeNumber == 0)
{
isPrime = false;
break;
}
}
if (isPrime)
{
count ++;
vector.addElement(new Integer(n));
if (count % NUMBER_PER_LINE == 0)
{
System.out.println(n);
}
else
System.out.print(n + " ");
}
}
}
}
PrimeByVector.java:15: error: not a statement
PrintWriter writer = null;
^
PrimeByVector.java:15: error: ';' expected
PrintWriter writer = null;
^
2 errors
最佳答案
在您的第一个for
(不适合身体!)循环之后立即:
PrintWriter writer = null;
try {
writer = new PrintWriter("VectorDump", "UTF-8");
} catch (Exception e) {
break;
}
Iterator it = vector.iterator();
while(it.hasNext())
{
writer.print(
it.next() + " "
);
}
writer.close();