public class isPrime { public static void main(String[] args) throws FileNotFoun
ID: 3668399 • Letter: P
Question
public class isPrime {
public static void main(String[] args) throws FileNotFoundException
{
isPrime primeNum = new isPrime();
for(int i=1;i<=9999;i++){
if ( primeNum.isPrime(i) ) {
System.out.printf(" Result: The number %d is Prime", i);
PrintWriter isPrime = new PrintWriter ("Created by John Xiang.txt");
isPrime.println(i);
isPrime.close();
} else {
System.out.printf(" Result: The number %d is not Prime", i);
}
}
}
How can I print all the prime results to TXT?
Explanation / Answer
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.PrintWriter;
public class isPrime {
public static void main(String[] args) throws FileNotFoundException {
isPrime primeNum = new isPrime();
try {
File file = new File("Xiang.txt");
if (!file.exists()) {
file.createNewFile();
}
FileWriter fw = new FileWriter(file.getAbsoluteFile());
BufferedWriter bw = new BufferedWriter(fw);
for (int i = 1; i <= 9999; i++) {
if (primeNum.isPrime(i)) {
System.out.printf(" Result: The number %d is Prime", i);
PrintWriter isPrime = new PrintWriter(
"Created by John Xiang.txt");
isPrime.println(i);
bw.write(i + " ");
isPrime.close();
} else {
System.out.printf(" Result: The number %d is not Prime",
i);
}
}
bw.close();
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* checks whether an int is prime or not.
*
* @param n
* @return
*/
public boolean isPrime(int n) {
for (int i = 2; i < n; i++) {
if (n % i == 0)
return false;
}
return true;
}
}
Xiang.txt
1
2
3
5
7
11
13
17
19
23
29
31
37
41
43
47
.
.
.
9941
9949
9967
9973
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.