Guest User

Untitled

a guest
Oct 23rd, 2017
74
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.70 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.         System.out.println(+maxNumber);
  23.         for(int i = 3; i <= maxNumber; ++i){
  24.                 if( number % i == 0) return true;
  25.         }
  26.         // no primes found;
  27.         return false;
  28. }
  29.  
  30. // part 3 - notify the user
  31.  
  32. public static void notifyUser(boolean numberIsPrime){
  33.         if(numberIsPrime){
  34.                 showMessageDialog(null, "Tallet er et primtall");
  35.         }
  36.         else{
  37.                 showMessageDialog(null, "Tallet er ikke et primtall");
  38.         }
  39. }
  40.  
  41.  
  42. public static void main(String[] args){
  43.         // lets tie it all together!
  44.         // read user inputs  one after the other, let the user know the results
  45.         int tallinput = 1; // lets define this here first to force the program run at least once
  46.         while (tallinput > 0){ //kjører programmet på nytt med mindre brukeren trykker cancel.
  47.                 tallinput = getInput();
  48.                 boolean isPrime = checkPrime(tallinput);
  49.                 notifyUser(isPrime);
  50.         }
  51.         return;
  52.     }
  53. }
Add Comment
Please, Sign In to add comment