1 year ago
#381604
James Rager
How do I generate a list of prime numbers up to 100 and output that to a .txt file in this Java program?
I've got an assignment that requires me to test if an integer entered by the user is prime. I've got a good base for a general test, but the assignment is combined with another problem that requires me to generate a list of all prime numbers from 1 to 100, then export that information as a .txt file. I'm a unsure of the formula I should use to make that list and how to print it to a file. Thank you for your time!
import java.io.*;
import java.util.Scanner;
public class PrimeNumberList
{
public static void main(String[] args) throws IOException
{
System.out.println("This program will check if an integer value " +
"entered by you use a prime number! \nIt will then generate a " +
"list of prime numbers from 1 - 100 in a .txt file!");
int userNumber;
Scanner keyboard = new Scanner(System.in);
System.out.print("Please enter a number or type 0 to generate " +
"the list and close the program: ");
userNumber = keyboard.nextInt();
while(userNumber > 0)
{
isPrime(userNumber);
if (isPrime(userNumber) == false)
{
System.out.println("That is not a prime number!");
}
else
System.out.println("That is indeed a prime number!");
System.out.print("Please enter a number or type 0 to generate " +
"the list and close the program: ");
userNumber = keyboard.nextInt();
}
while(userNumber = 0);
{
String filename;
System.out.print("Please enter a name for your file: ");
filename = keyboard.nextLine();
Printwriter outputFile = new PrintWriter(filename);
for (int num = 0; num < 100; num++)
{
//Here is where I want to generate a list of all
//prime numbers up to 100 and output that to a file.
}
}
}
public static boolean isPrime(int userNumber)
{
for(int i = 2; i < userNumber; i++)
{
if(userNumber % i == 0)
{
return false;
}
}
return true;
}
}
java
loops
methods
primes
printwriter
0 Answers
Your Answer