Saturday, 21 January 2017

Chapter 22 Exercise 12, Introduction to Java Programming, Tenth Edition Y. Daniel LiangY.

22.12 (Last 100 prime numbers) Programming Exercise 22.8 stores the prime numbers in a file named PrimeNumbers.dat. Write an efficient program that reads the last 100 numbers in the file. (Hint: Don’t read all numbers from the file. Skip all numbers before the last 100 numbers in the file.)


import java.io.*;

public class Exercise12 {

 public static void main(String[] args) throws IOException {
  DataInputStream input = new DataInputStream(new BufferedInputStream(new FileInputStream("PrimeNumbers.dat")));
  int primeNumbers = 100;
  input.skipBytes(input.available() - 8 * primeNumbers);
  for (int i = 0; i < primeNumbers; i++) {
   System.out.println(input.readLong());
  }
  input.close();   
 }
}

No comments :

Post a Comment