Re: Prime Numbers Help Java
I'm not sure why you want to output a n x n table or what values you intend to put in it so I can only give a generalised answer. You could do it using nested loop ie
Code:
for (int i = 0; i < num; i++) {
for (int j = 0; j < num; j++) {
// output the value here for row i, column j
System.out.print(myVals[i][j]);
}
System.out.println();
}
You'll need to pad each columns output to make sure all the columns line up. You could do this by adding spaces or using printf with the appropriate formatting characters.
Re: Prime Numbers Help Java
The table should show the prime numbers in a table.
Say the user enters 5, it prints a 5x5 table of all the prime numbers that can fit into that specified value.
What should I put in the second part of the printf statement: ...("%4d, ____)
Re: Prime Numbers Help Java
This doesn't make much sense. Is this an assignment? I think you have the requirement wrong.
If I give you the number 142,775 (a relatively small number), are you really going to try and display on the console a 142,775 X 142,775 two dimensional table of a subset of prime numbers within that range? that doesn't make any sense at all.
You'll have to figure out how you'll want to format it, or paginate your results, etc.
Re: Prime Numbers Help Java
Say for e.g.
User enters 2
It would print a 2X2 table looking like this:
2 3
5 7
This is what I mean.
But what I have so far prints something else. This snippet I put in main after the if else block determining if it is prime or not.
Code:
for(int x=1; x<=n; x++){
for(int y=1; y<=n; y++)
System.out.printf("%4d",x%y); // is it suppose to be x%y or what?
System.out.println();
}
Re: Prime Numbers Help Java
Ok so I suggest three things:
1) Do some bounds checking. Probably something larger than say 14 x 14 won't display properly anyways. This is what I was saying before. If I type in 144,204 or some other large number, you'll sit there for seconds; minutes; hours; etc. depending on the size trying to compute this. Prime number calculation can be optimized with shifting operations / etc. but that's another story.
2) Use what keang said. two nested loops. both betwen i = 0; and user inputted number. Format them with printf or something similar (tab seperated or something similar)
3) write yourself a method like int getNextPrime(), keep track of the last known prime number, and return the next valid prime number to print out. then inside your loops you just print out the return of this method.
Practically here, you could test your loop logic by just printing out something hard coded like
Code:
System.out.println("x");
and later switch that to
Code:
System.out.println(getNextPrime());
once you write that method (or however else you want to do it).
This is an important topic to keep in mind: seperate your business logic from your presentation logic.
Re: Prime Numbers Help Java
This program should only utilize the isPrime method. Not allowed to use another method.
Maybe the nested for loop is wrong?
Can someone check to see if the variables were just mixed up?
Re: Prime Numbers Help Java
As Deliverance has said you need to seperate business and presentation logic. You need to do this in your head as well as your code. You have two distinct problems here the first is to compute the first n prime numbers so I suggest you do that and store them in an array. The second is to display the results in a grid format using the process previously outlined. Trying to do this in one go adds unnecessary complication and confusion as well as being bad practice.
Re: Prime Numbers Help Java
I tried it out, can you help me with implementing it, like where should I put this piece of code?
Code:
public static int getNextPrime(int n){
int myVals= new myVals[1000][]; //Something wrong with array.
if(n==2)
return n;
else
for (int i = 0; i < num; i++) {
for (int j = 0; j < num; j++) {
// output the value here for row i, column j
System.out.print(myVals[i][j]);
}
System.out.println();
}
}
Re: Prime Numbers Help Java
so you read the variable from the user and stored it in 'n'.
Code:
int n = 6;
for(int outerVariable = 0; outerVariable < n; outerVariable++) {
for(int innerVariable = 0; innerVariable < n; innerVariable++) {
System.out.print("\t" + "X");
}
System.out.println("");
}
stick that into a main method and run that as a test case.
Here i print out a grid of X's given any input size. Once you can do that, then worry about where to grab your next prime number from. This is a primitive example, but shows you that you have two problems to solve, and is much easier if you separate the two:
a calculation problem (business logic)
a presentation problem (presentation logic, how do you display and format your grid). Note that this only uses one tab in between, and i'm sure the grid won't look good with large numbers / etc. that span a larger width than 8 characters which I think is what a tab is by default. but you get the idea. split up your problems into smaller more manageable units of work!
Re: Prime Numbers Help Java
Revised Code:
My new getPrime method is giving me trouble.
Code:
import java.util.*;
public class PrimeNumbersTable {
public static Scanner scanner = new Scanner(System.in);
// Reads and returns an int, handling the case of non-int input.
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();
}
// It returns true if n is prime. First checks if n is even, handling the
// cases of n=2 (prime) or n is even > 2 (not prime). Then checks if any
// odd #'s between 3 and sqrt(n), inclusive, are divisors of n, returning
// false if any are.
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;
}
//New method created to get the prime number and return it
public static int getPrime(int x){
if(isPrime()!=false){
return x;
//For loop here?
// for(int b=0;b<=n;b++){
// for(int c=0; c<=n;c++)
// System.out.println("%4d", x);
// System.out.println();
// }
//System.out.println("x is: " +x);
}
}
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);
for(int x=1; x<=n; x++){
for(int y=1; y<=n; y++)
System.out.println("Results: " +getPrime(n)); //Calls the method to get results
System.out.printf("%4d", x%n);
System.out.println();
}
}
}
Re: Prime Numbers Help Java
Quote:
My new getPrime method is giving me trouble.
Please put some effort and detail into your posts, we not mind readers. What sort of trouble? Is there a compile or run time error message? Is it just not working, if so what is it doing amd what did you expect it to do?
1. Do you have an isPrime() method that takes no arguements?
2. What value will you be passing into getPrime() (which probably should be called getNextPrime), if it's the last prime number you found then you probably shouldn't be testing to see if the value passed in is a prime or you will never get the next prime.
Re: Prime Numbers Help Java
It might help to work out the steps that are required separately from writing the code. Decide what has to be done step by step in English (on paper), then translate it into code.
Rewrite and revise. Do not be afraid to seize what you have and cut it to ribbons ... Good writing means good revising...
W Strunk Jr
Re: Prime Numbers Help Java
given
Code:
static Integer currentPrime = 1; //field of your class
public static int getNextPrime() {
while(!isPrime(currentPrime)) {
currentPrime++;
}
return currentPrime;
}
will always return you the next prime number.
I don't get why you keep changing your loops, or whether you don't realize that you are printing out a
Code:
System.out.println("Results: " +getPrime(n));
for each iteration.
Code:
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
System.out.printf("%6d", getNextPrime());
currentPrime++;
}
System.out.println();
}
all you need. Make the width something wider (i moved it to 6) because you'll start to see collision when you get prime numbers in the thousands.