Guest User

Untitled

a guest
Oct 23rd, 2017
64
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.71 KB | None | 0 0
  1. import static javax.swing.JOptionPane.*;
  2.  
  3. public class primtall2 { //class start
  4.  
  5. // part 1 - get the user input
  6. public static int getInput(){
  7.         String tallinput = showInputDialog("Skriv inn et tall");
  8.         int number = Integer.parseInt(tallinput);
  9.         return number;
  10. }
  11.  
  12.  
  13. // part 2 - check if the number is prime
  14.  
  15. // functions are run from top to bottom, so it's perfectly okay to just quit early
  16. // an early return like this is much more readable than nested ifs
  17. public static boolean checkPrime(int number){
  18.         if(number == 2) return true;
  19.         if(number == 1) return true;
  20.         if(number%2==0) return false;
  21.         int maxNumber = (int)Math.floor(Math.sqrt(number));
  22.         for(int i = 3; i <= maxNumber; ++i){
  23.                 if( number % i == 0) return false;
  24.         }
  25.         // no primes found;
  26.         return true;
  27. }
  28.  
  29. // part 3 - notify the user
  30.  
  31. public static void notifyUser(boolean numberIsPrime, int number){
  32.         if(numberIsPrime){
  33.                 showMessageDialog(null, "Tallet "+number+" er et primtall");
  34.         }
  35.         else{
  36.                 showMessageDialog(null, "Tallet "+number+" er ikke et primtall");
  37.         }
  38. }
  39.  
  40.  
  41. public static void main(String[] args){
  42.         // lets tie it all together!
  43.         // read user inputs  one after the other, let the user know the results
  44.         int tallinput = 1; // lets define this here first to force the program run at least once
  45.         while (tallinput > 0){ //kjører programmet på nytt med mindre brukeren trykker cancel.
  46.                 tallinput = getInput();
  47.                 boolean isPrime = checkPrime(tallinput);
  48.                 notifyUser(isPrime, tallinput);
  49.         }
  50.         return;
  51.     }
  52. }
Add Comment
Please, Sign In to add comment