daily pastebin goal
20%
SHARE
TWEET

Untitled

a guest May 17th, 2018 100 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. package com.example.yarik.lab1;
  2.  
  3. import android.app.AlertDialog;
  4. import android.app.Dialog;
  5. import android.os.Bundle;
  6. import android.support.annotation.NonNull;
  7. import android.support.v4.app.DialogFragment;
  8.  
  9. public class CustomDialogFragment extends DialogFragment {
  10.     @NonNull
  11.     public Dialog onCreateDialog(Bundle savedInstanceState) {
  12.         String fromText = getArguments().getString("firstNumber");
  13.         String toText = getArguments().getString("secondNumber");
  14.         String operationString = getArguments().getString("operationText");
  15.         Double result = 0.0;
  16.         boolean failed = false;
  17.         try {
  18.             Double firstNumber = Double.parseDouble(fromText);
  19.             Double secondNumber = Double.parseDouble(toText);
  20.  
  21.             char operation = operationString.charAt(0);
  22.             result = calculate(firstNumber, secondNumber, operation);
  23.         } catch (Throwable t) {
  24.             failed = true;
  25.         }
  26.         AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
  27.         if (failed) {
  28.             return builder
  29.                     .setTitle("ERROR!")
  30.                     .setMessage("You've provided incorrect input!")
  31.                     .setPositiveButton("I'll try to be better next time", null)
  32.                     .create();
  33.         } else return builder
  34.                 .setTitle("Result of operation")
  35.                 .setIcon(android.R.drawable.ic_dialog_info)
  36.                 .setMessage("Result = " + result)
  37.                 .setPositiveButton("OK", null)
  38.                 .create();
  39.     }
  40.  
  41.     private Double calculate(Double firstNumber, Double secondNumber, char operation) {
  42.         switch (operation) {
  43.             case '+':
  44.                 return firstNumber + secondNumber;
  45.             case '-':
  46.                 return firstNumber - secondNumber;
  47.             case '*':
  48.                 return firstNumber * secondNumber;
  49.             case '/':
  50.                 return firstNumber / secondNumber;
  51.         }
  52.         throw new NumberFormatException();
  53.     }
  54. }
RAW Paste Data
Top