到目前为止,我有以下代码....我导入一个带有数字的文件并测试它们是否是素数。我应该将素数输出到一个单独的文件中,但我无法将“isPrime”方法中的数字(测试#是否为素数)移动到“Main”方法。
public static void main(String[] args)throws IOException
{
int x, input;
String filename, filename2;
Scanner k = new Scanner (System.in);
System.out.println("Hello, please enter an input file name!");
filename = k.nextLine();
System.out.println("Hello, please enter an output file name!");
filename2 = k.nextLine();
File file = new File(filename);
Scanner inputFile = new Scanner(file);
while (inputFile.hasNext())
{
input = inputFile.nextInt();
inputFile.close();
isPrime(input);
}
PrintWriter outputFile = new PrintWriter("C\\Desktop\\"+filename2);
}
public static boolean isPrime(int n) {
for(int i=2;i<n;i++) {
if(n%i==0)
return false;
}
return outputFile.println(n);
}
答案 0 :(得分:0)
您的代码中存在一些错误:
AutoCloseable
接口。isPrime(int)
返回boolean
并依赖它决定是否写号码。我已经重写了你的代码,看看这个:
public static void main(String[] args) {
Scanner userInputScanner = new Scanner(System.in);
System.out.println("Please enter the path for numbers file: ");
String inputNumberFilePath = userInputScanner.nextLine();
System.out.println("Please enter the path for the output file: ");
String outputNumberFilePath = userInputScanner.nextLine();
try (Scanner inputNumberFileReader = new Scanner(new File(inputNumberFilePath)); PrintWriter outputFile = new PrintWriter(outputNumberFilePath);) {
while (inputNumberFileReader.hasNext()) {
int num = inputNumberFileReader.nextInt();
if (isPrime(num)) {
outputFile.println(num);
}
}
} catch (Exception ex) {
System.out.println(ex);
} finally {
if (userInputScanner != null) {
userInputScanner.close();
}
}
}
public static boolean isPrime(int num) {
for (int i = 2; i < num; i++) {
if (num % i == 0)
return false;
}
return true;
}