I'm trying to write a file that first decides if a number entered is prime or not, then if it is writes it to a file. Here's what I've got, but I keep coming up with a couple errors that I can't figure out how to fix. One is that I can't figure out how to bring the number into the second method (which I have to use). I'm also not sure I'm using the write way to write to file. Help?

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

    int num; 

        Scanner keyboard = new Scanner(System.in);

        System.out.println("Please enter a positive integer: ");

        num = keyboard.nextInt();



        for (int x=2; x < num; x++)

        {
            if (num%x==0)
                noPrime();
            else 
                prime();

        }
        System.exit(0);
   }
    public static void prime(int num)
    {

            System.out.println(num + " is prime.");

            while (num <=100 && num >=1);
            {


                //Open the file.
                PrintWriter outputFile = new PrintWriter(PrimeNumbers.txt);

                //Write number to the file.
                outputFile.println(PrimeNumbers.txt);

                //Close the file.
                outputFile.close();
                System.out.println("Numbers written to file.");
            }


    }

    public static void noPrime(int num)
    {
        System.out.println(num + " is not prime.");
    }


}//end class

Recommended Answers

All 2 Replies

Can't you read the errors and follow the instructions to fix them? When you get compile errors you get a description of the error, the line that it happened and how to fix it.

Why doesn't anybody read compile errors these days and just post the code without even bothering to see what the compiler says??

And most important, you didn't even post these errors, you just gave us the code. Are we suppose to compile it for you in order to find out the errors?

Anyway, you declare prime and noPrime like this:
public static void noPrime(int num)
public static void prime(int num)
and you use them like this:
noPrime();
prime();

You figure it out.

Also I think that you are missing the main method and this piece of code:

Scanner keyboard = new Scanner(System.in);
System.out.println("Please enter a positive integer: ");
num = keyboard.nextInt();

for (int x=2; x < num; x++)
{
if (num%x==0)
noPrime();
else
prime();
}
System.exit(0);
}

is not inside a method, it's in the middle of the class

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.