0

编写一个程序来读取数字列表,确定它们是否是素数,然后将它们写入文件。早些时候发布了这个问题..修复了我的逻辑以确定数字是否为素数。现在我看不到让它写入名为“PrimeNumbers.txt”的文本文件

在某一时刻,我让它能够写一行,但现在没有任何东西写入文本文件。请指教。

import java.io.*;
import java.util.Scanner;

public class AssignFive_FileRead {
public static void main(String[] args) throws IOException {

int number; 
int count = 0;
int calc = 0;
int i = 2;

File myFile = new File("assignment5Numbers.txt");
File myTargetFile = new File("PrimeNumbers.txt");
Scanner inputFile = new Scanner(myFile);

System.out.println("** Checking for required files **");

// Check to see if file's exists

if (!myTargetFile.exists()) {
  System.out.println("Error: Unable to create target file!");
  System.exit(0);
} else {
  System.out.println("Target file has been created!");
}

if (!myFile.exists()) {
  System.out.println("Error: file cannot be found");
  System.exit(0);
} else {
  System.out.println("Source file has been found, starting operation...");
  System.out.println();
}

  // Reading numbers from text file
  while (inputFile.hasNext()) {
  number = inputFile.nextInt();

  while (i <= number / 2) {
     if (number % i == 0) {
        calc = 1;
     }
     i++;
  } // End second while loop

  if (calc != 1) {     
     count++;
     for (int x = 0; x <= count; x++) {
     PrintWriter outputFile = new PrintWriter("PrimeNumbers.txt");
     outputFile.print(number + "\t");
     outputFile.println("is prime");
     }
  } 

  // resetting variables for next check
  calc = 0;
  i = 2;

} // End first while loop

// System.out.println("Source file has a total of " + count + " numbers");

System.out.println("Data has been written to files.. Operation successful!");

 } // End main 
} // End public class
4

1 回答 1

1
  1. 将您的循环标记在循环PrintWriter outputFile之外while,您将重用PrintWriter并且您希望将其当前内容/位置保留在文件中,因此每次解析另一个数字时都不应该重新声明它。还要重命名它,名称不代表它的作用,称它为outputWriter.

  2. 您需要.close()输入和输出流,这可以确保缓冲区已被刷新并且资源已从 Java 应用程序中释放。之前:System.out.println("Data has been written to files.. Operation successful!");outputFile.close();inputFile.close();

于 2014-10-14T02:34:23.897 回答