Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import static javax.swing.JOptionPane.*;
- public class primtall2 { //class start
- // part 1 - get the user input
- public static int getInput(){
- String tallinput = showInputDialog("Skriv inn et tall");
- int number = Integer.parseInt(tallinput);
- return number;
- }
- // part 2 - check if the number is prime
- // functions are run from top to bottom, so it's perfectly okay to just quit early
- // an early return like this is much more readable than nested ifs
- public static boolean checkPrime(int number){
- if(number == 2) return true;
- if(number == 1) return true;
- if(number%2==0) return false;
- int maxNumber = (int)Math.floor(Math.sqrt(number));
- System.out.println(+maxNumber);
- for(int i = 3; i <= maxNumber; ++i){
- if( number % i == 0) return true;
- }
- // no primes found;
- return false;
- }
- // part 3 - notify the user
- public static void notifyUser(boolean numberIsPrime){
- if(numberIsPrime){
- showMessageDialog(null, "Tallet er et primtall");
- }
- else{
- showMessageDialog(null, "Tallet er ikke et primtall");
- }
- }
- public static void main(String[] args){
- // lets tie it all together!
- // read user inputs one after the other, let the user know the results
- int tallinput = 1; // lets define this here first to force the program run at least once
- while (tallinput > 0){ //kjører programmet på nytt med mindre brukeren trykker cancel.
- tallinput = getInput();
- boolean isPrime = checkPrime(tallinput);
- notifyUser(isPrime);
- }
- return;
- }
- }
Add Comment
Please, Sign In to add comment