📄 example0601_io.java
字号:
/* 设计一个应用程序,从键盘输入一个整数n,
* 然后在文件"data.dat"中写入所有比n小的素数,
* 最后在屏幕上显示在每个素数中各数字(0--9)出现的次数
*/
import java.io.*;
public class Example0601_IO
{
public static boolean isPrime(int n)
{
for (int i = 2 ; i <= n/2 ; i++)
{
if (n % i == 0) return false;
}
return true;
}
public String getDigitAppearanceCount(int n)
{
StringBuffer s = new StringBuffer("\n素数 " + n + " 中各数字出现的次数如下:\n");
int[] c = new int[10];
while (n != 0)
{
c[n % 10]++;
n /= 10;
}
for (int i = 0 ; i < 10 ; i++)
{
if (c[i] != 0) s.append("count(" + i + ") = " + c[i] + "\n");
}
return s.toString();
}
public static void main(String[] args)
{
try
{
System.out.print("Please input n = ");
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
String strn = reader.readLine();
int n = Integer.parseInt(strn);
DataOutputStream output = new DataOutputStream(new FileOutputStream("data.dat"));
for (int i = 2 ; i <= n ; i++)
{
if (isPrime(i))
{
System.out.println(new Example0601_IO().getDigitAppearanceCount(i));
output.writeInt(i);
}
}
output.close();
/* 下面的程序段用于读取文件的内容并输出
DataInputStream input = new DataInputStream(new FileInputStream("data.dat"));
while (input.available() > 0)
{
System.out.println(input.readInt());
}
input.close();
**************************************/
/* 下面的程序段使用PrintStream流类输出数据
PrintStream output2 = new PrintStream(new FileOutputStream("data.txt"));
for (int i = 2 ; i <= n ; i++)
{
if (isPrime(i))
{
output2.printf("%d ",i);
}
}
output2.close();
**************************************/
}
catch (IOException e)
{
System.out.println(e.getMessage());
}
catch (NumberFormatException e)
{
System.out.println(e.getMessage());
}
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -