example06_primen.java

来自「java课程设计教材上的程例题序代码」· Java 代码 · 共 55 行

JAVA
55
字号
package example;

import java.io.*;

import javax.swing.JOptionPane;

public class Example06_PrimeN {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub

		int n = Integer.parseInt(JOptionPane.showInputDialog(null,
				"Enter a number"));
		File file = new File("primen.dat");
		DataOutputStream dos;
		try {
			dos = new DataOutputStream(new FileOutputStream(file));

			for (int i = 2; i <= n; i++) {
				if (isPrime(i))
					dos.writeInt(i);
			}

			dos.close();

			String mes = "";
			RandomAccessFile raf = new RandomAccessFile(file, "r");
			for (int i = 1; i <= (int) (raf.length() / 4); i++) {
				mes += raf.readInt() + "  ";
			}
			if (mes.isEmpty())
				mes = "None";
			
			raf.close();

			JOptionPane.showMessageDialog(null, mes);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	public static boolean isPrime(int n) {
		for (int i = 2; i <= (int) Math.sqrt(n); i++) {
			if (n % i == 0)
				return false;
		}

		return true;
	}

}

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?