Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Java

Help! Task: Ask for int, check if primenumber, print answer. Loop until forced to shut (ESC if using .showInputDialog())

Hi,

I have an assignment to make a program that keeps asking for input, checks if input is prime, and prints result, looping through this until forced to stop. Psuedocode i have written is(not good a pseudocode...):

  • Ask user for a whole number. (ie. String prime = showInputDialog("Int please: ");)
  • convert number to int (int maybePrime = Integer.parseInt(prime)
  • Check if int is a prime.
  • If maybePrime is a prime, print "is prime" (ie. showMessageDialog(null, "Is prime"; && System.out.println("Is a prime");)
  • if maybePrime is not prime, print "is not prime" (ie. showMessageDialog(null, "Is not prime"; && System.out.println("Is not a prime");)) -Ask user for int.
  • Loop until program is forced to shut. (ie. if using .showInputDialog(), stop program when ESC is pressed)

How would the actual formula for the prime number go? I know there is no exact formula for finding primes (if you have one, get ready to be famous!), but lets say i want to check numbers from 1-50. Been looking on the web for ages not finding a good answer to implement to Java while running it in a loop.

Hope someone can help me out here. if not, maybe this is a brain twister for some of the more experienced coder to have fun trying.

Regards Chris

1 Answer

Maybe this is what you're looking for: https://en.wikipedia.org/wiki/Primality_test