Advertisement
Voldemord

JedrykaNWD na 5

Mar 7th, 2019
172
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.77 KB | None | 0 0
  1. /* -------------Plik Main -------- */
  2.  
  3. package zadanie1a;
  4.  
  5. public class Main {
  6.  
  7.     public static void main(String[] args) {
  8.         try {
  9.             Nwd n = new Nwd(1, 20);
  10.             n.setB(0);
  11.             System.out.println("Dla a = " + n.getA() + " oraz B = " + n.getB() + " NWD wynosi: " + n.getNwd() + " lub: -" + n.getNwd());
  12.         } catch (Exception e) {
  13.             System.out.println("\u001B[31m"+ "NWD nie obsługuje 0" + "\u001B[0m");
  14.             e.printStackTrace(System.out);
  15.         }
  16.  
  17.     }
  18. }
  19.  
  20.  
  21.  
  22. /* -------------Plik classa NWD -------- */
  23.  
  24. package zadanie1a;
  25.  
  26. public class Nwd {
  27.  
  28.     private int a;
  29.     private int b;
  30.     private int nwd;
  31.  
  32.     public Nwd(int a, int b) throws Exception{
  33.          if (a == 0 || b == 0) throw new Exception("NWD nie obsługuje 0");
  34.             this.a = a;
  35.             this.b = b;
  36.             nwd();
  37.     }
  38.  
  39.     private void nwd(){
  40.         int a = this.a;
  41.         int b = this.b;
  42.        
  43.         /* Fixing problems */
  44.        
  45.         if (a < 0) a = Math.abs(a);
  46.         if (b < 0) b = Math.abs(b);
  47.  
  48.         while (a != b) {
  49.             if (a > b) {
  50.                 a = a - b;
  51.             } else {
  52.                 b = b - a;
  53.             }
  54.         }
  55.         this.nwd = a;
  56.     }
  57.  
  58.     public int getA() {
  59.         return a;
  60.     }
  61.  
  62.    
  63.     public void setA(int a) throws Exception{
  64.         if(a == 0) throw new Exception("A nie moze przyjąć wartości 0");
  65.         this.a = a;
  66.         nwd();
  67.     }
  68.  
  69.     public int getB() {
  70.         return b;
  71.     }
  72.  
  73.    
  74.     public void setB(int b) throws Exception{
  75.         if(b == 0) throw new Exception("B nie moze przyjąć wartości 0");
  76.         this.b = b;
  77.         nwd();
  78.     }
  79.  
  80.     public int getNwd() {
  81.         return nwd;
  82.     }
  83.  
  84.  
  85. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement