我正在创建一个保存第一个 X 素数的程序,但是当我将其保存ArrayList
到文本文件时,列表完全错误。这是我的代码:
import java.util.Scanner;
public class Class1
{
// This method tests whether a given number is prime or not.
public boolean isPrime ( int num )
{
boolean prime = true;
int limit = (int) Math.sqrt ( num );
for ( int i = 2; i <= limit; i++ )
{
if ( num % i == 0 )
{
prime = false;
break;
}
}
return prime;
}
public static void main ( String[] args )
{
Class1 ob1=new Class1();
System.out.println("Where do you want to stop?");
Scanner scan = new Scanner(System.in);
int y = scan.nextInt();
for ( int i = 2; i <= y; i++ )
{
if ( ob1.isPrime ( i ) )
System.out.println ( i );
}
}
}
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.util.ArrayList;
import java.util.List;
public class Output {
public static void main(String args[]) throws IOException {
Class1 obj = new Class1();OutputStream outputstream = new FileOutputStream("write.txt");
Writer writer1 = new OutputStreamWriter(outputstream);
try{
int max =100;
List<Integer> record = new ArrayList<Integer>(max);
// Going write in this file
for ( int i = 2; i <= max; i++ )
{
if ( obj.isPrime ( i ) )
System.out.println ( i );
record.add(i);
}
for(Integer str: record){
writer1.write(str);
}
}catch(IOException e){
}finally{writer1.close();}
}
}
这就是文本文件的样子:
!"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\