|
-
July 21st, 2009, 07:15 PM
#1
Prime Numbers Help Java
So I've created a program which outputs whether the user entered a prime or not.
Now, how do I output it so that for e.g: The user enter 5, it prints a 5X5 table.
The dimensions of the table is determined based on the number the user enters.
Code:
import java.util.*;
public class IsPrime {
public static Scanner scanner = new Scanner(System.in);
public static int readInt() {
System.out.print("Enter an integer: ");
while (!scanner.hasNextInt()) {
scanner.next();
System.out.print("That was not an integer. Please try again: ");
}
return scanner.nextInt();
}
public static boolean isPrime(int n) {
if (n < 2) return false;
if (n % 2 == 0)
// n is an even, so it returns true if n is exactly 2.
return (n == 2);
for (int i=3; i*i<=n; i+=2)
if (n % i == 0)
// i divides evenly into n, so n is not prime
return false;
return true;
}
public static void main(String[] args) {
System.out.println("Prime Numbers\n");
int n = readInt();
if (isPrime(n))
System.out.printf("%d is a prime.\n",n);
else
System.out.printf("%d is not a prime.\n",n);
//The part that I don't think is right.
//for(n=1; n<=12; n++){
// for(int y=1; y<=12; y++)
//System.out.printf("%4d",n%y);
//}
}
}
Last edited by coder752; July 21st, 2009 at 08:24 PM.
Tags for this Thread
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|