Advertisement
Paarzivall

Untitled

Mar 18th, 2019
83
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.07 KB | None | 0 0
  1. package zajęcia3;
  2.  
  3. import java.util.Scanner;
  4.  
  5. public class wyjatek_cw {
  6.  
  7.     public static void main(String[] args) {
  8.         while(true) {
  9.             try {
  10.                 funkcja();
  11.                 break;
  12.             }
  13.             catch(NieLiczba e) {
  14.                 System.out.println(e.getMessage());
  15.                 continue;
  16.             }
  17.             catch(Ujemna e) {
  18.                 System.out.println(e.getMessage());
  19.                 continue;
  20.             }
  21.         }
  22.     }
  23.    
  24.     private static void funkcja() throws NieLiczba, Ujemna{
  25.         Scanner sc = new Scanner(System.in);
  26.         System.out.println("Podaj liczbę: ");
  27.        
  28.         while(sc.hasNextDouble()) {
  29.             double liczba = sc.nextDouble();
  30.             if(liczba > 0)
  31.                 System.out.println("Pierwiastek z liczby " + liczba + " wynosi: " + pierwiastek(liczba));
  32.             else
  33.                 throw new Ujemna();
  34.         }
  35.         throw new NieLiczba();
  36.     }
  37.    
  38.     private static double pierwiastek(double x) {
  39.         return Math.sqrt(x);
  40.     }
  41. }
  42.  
  43. class NieLiczba extends Exception{
  44.     public NieLiczba() {
  45.         super("Nie podałeś liczby!!!");
  46.     }
  47. }
  48.  
  49. class Ujemna extends Exception{
  50.     public Ujemna() {
  51.         super("Podałeś liczbę ujemną! Nie można z niej wyciągnąć pierwiastka :(");
  52.     }
  53. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement