Java程序中的逻辑错误

时间:2014-10-10 15:36:45

标签: java

编写一个程序,从文本文件中读取数字并测试它们以查看它们是否为素数。文本文件由以下数字组成:98,76,84,69,92,83,88,90,72,66。第一个数字,98不是素数,但第二个数字(76)应该作为Prime 。我打印出的结果显示所有数字都是Not Prime,但这不是真的。

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

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

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

File myFile = new File("Numbers.txt");
Scanner inputFile = new Scanner(myFile);

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

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

  // Begin calculation to see if number is prime
  while (i <= number / 2) {
     if (number % i == 0) {
        calc = 1;
     }
     i++;
  } // End second while loop

  if (calc == 1) {
     System.out.println("Number: " + number + " is Not Prime!");
  } else {
     System.out.println("Number: " + number + " is Prime!"); 
  }

} // End first while loop

} // End main 
} // End public class

3 个答案:

答案 0 :(得分:5)

您的代码中存在错误(我刚发现它)。

但是,最大的错误在于您的测试方法。

你说76是素数。事实并非如此。 7638 x 2,这意味着它不是素数。 (实际上,任何均匀且大于2的正数都不是素数......)

事实上,83是该列表中唯一的素数。

答案 1 :(得分:1)

每当你读一个数字

时,

初始计算

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

    // Begin calculation to see if number is prime
    calc = 0;
    while (i <= number / 2) {
    // [...]

答案 2 :(得分:-1)

每次从第二次循环中退出时,都应重置i和calc。我已使用以下代码修复它

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

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

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

File myFile = new File("input.txt");
Scanner inputFile = new Scanner(myFile);

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

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

  // Begin calculation to see if number is prime
  while (i <= number / 2) {
     if (number % i == 0) {
        calc = 1;
     }
     i++;
  } // End second while loop

  if (calc == 1) {

     System.out.println("Number: " + number + " is Not Prime!");
  } else {
     System.out.println("Number: " + number + " is Prime!"); 
  }
  calc = 0;
  i=2;

} // End first while loop

} // End main 
} // End public class