找到并将所有素数1-100打印到文件的程序

时间:2017-11-22 03:33:02

标签: java

我有一份家庭作业,我被困住了。程序编译得很好但是当我运行它时,它只将数字1打印到文件中并结束。我已经搜索了几十次这个问题,所有的解决方案都涉及尝试和捕捉我的教授不会接受的陈述,因为我们还没有在课堂上学到它。 这是我的代码:

`import java.util.Scanner;
import java.io.*;
public class K_Topple_Chap5_Prime_NumList_Redo
{
  public static void main(String[] args) throws IOException
  {
    String filename; //filename used to open file
    boolean isPrime;
    int num1 = 1;

    Scanner keyboard = new Scanner(System.in); //needed for scanner class

    System.out.print("Enter a directory for a file: "); //asks user for name 
of file
     filename = keyboard.nextLine(); //sets input equal to filename

    File file = new File(filename); //sets input filename = file variable
    Scanner inputFile = new Scanner(file); //opens file
    PrintWriter printWriter = new PrintWriter(file); //creates printwriter 
for file

    for(num1 = 1; num1 <= 100; num1++) //for statement that runs 98 times to 
test every number between 1-100 for primality
    {
      isPrime = isPrime(num1); //calls isprime method and tests primality 
and sets isPrime to boolean value
      if(isPrime == true) //if isPrime is true then it prints that number to 
the file
      {
        printWriter.println(num1 + " "); //prints num1 to file
      }
    }
    System.out.println("Done."); //when the for statement is done running it 
prints done
    printWriter.close (); //closes file
  }

  /**This method tests if a number is prime
    * @param num1 holds the current number being tested
    * @return returns true or false if number is prime or not
    * 
   */
  public static boolean isPrime(double num1) //isprime method used to test 
if a number is prime
  {
    int i;
    for (i = 2; i <= num1; i++) 
     {
      if (num1 % i == 0) 
       {
        return false;
       }
     }
    return true;
  }
}
`

我尝试发表评论以便让人们更容易理解,感谢任何帮助。感谢。

2 个答案:

答案 0 :(得分:1)

由于每个数字都可以被数字本身整除,因此您将从函数中获得false。只需将循环条件从i <= num1更改为i < num1即可。

for (i = 2; i < num1; i++) {
    if (num1 % i == 0) {
        return false;
    }
}

答案 1 :(得分:0)

这将返回正确的标志.u可以维护一个标志,并根据该标志返回true或false。

int i,flag=0;
for (i = 2; i <= num1/2; i++) 
 {
  if (num1 % i == 0) 
   {
     flag=1;      
     return true;   
   }
 }
if(flag==0)
return flase;