Binary01.java
Input file:
int1to100.txt
Select all
/* SimpleFileIO.java David Klick 2009-01-20 CIS 260 This program reads in integers from a file and writes the prime numbers it reads to another file. */ import java.io.FileNotFoundException; import java.io.FileReader; import java.io.PrintWriter; import java.util.Scanner; public class SimpleFileIO { public static void main(String[] args) throws FileNotFoundException { Scanner in = new Scanner(new FileReader("int1to100.txt")); PrintWriter out = new PrintWriter("primes1to100.txt"); int count = 0; while (in.hasNextInt()) { int i = in.nextInt(); if (isPrime(i)) { count++; out.println(i); } } in.close(); out.close(); System.out.println(count + " primes were found."); } private static boolean isPrime(int n) { if (n < 2) return false; int limit = (int) Math.sqrt(n); for (int i=2; i<=limit; i++) { if (n % i == 0) return false; } return true; } }