Exemple #1
0
 public static void main(String[] args) {
   int n = 0;
   int m = 0;
   while (true) {
     try {
       BufferedReader sisse = new BufferedReader(new InputStreamReader(System.in));
       System.out.println("V2ljumiseks vajutage ctrl-C");
       System.out.print("Laste arv: ");
       String s = sisse.readLine();
       n = Integer.parseInt(s);
       if (n < 0) throw new IllegalArgumentException(String.valueOf(n));
       System.out.print("6unte arv: ");
       s = sisse.readLine();
       m = Integer.parseInt(s);
       if (m < 0) throw new IllegalArgumentException(String.valueOf(m));
       System.out.println(
           "Igale lapsele "
               + String.valueOf(m / n)
               + " 6una ja "
               + String.valueOf(m % n)
               + " j22b yle");
     } catch (NumberFormatException e) {
       System.out.println("Ei ole arv: " + e.toString());
     } catch (ArithmeticException e) {
       System.out.println("Aritmeetikakatkestus: " + e.toString());
     } catch (Exception muu) {
       System.out.println("Probleem: " + muu.toString());
     } finally {
       System.out.println("n = " + n + "  m = " + m);
     }
   }
 } // main
 public static void main(String[] args) {
   try {
     divisionByZero();
   } catch (ArithmeticException e) {
     e.printStackTrace();
   }
 }
  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    Bundle extras = getIntent().getExtras();

    final Input input = (Input) extras.getSerializable(INPUT);

    try {
      this.expression = Expression.valueOf(input.getExpression());
      this.variable = new Constant(input.getVariableName());

      String title = extras.getString(ChartFactory.TITLE);
      if (title == null) {
        requestWindowFeature(Window.FEATURE_NO_TITLE);
      } else if (title.length() > 0) {
        setTitle(title);
      }

      setContentView(R.layout.calc_plot_view);

      final Object lastNonConfigurationInstance = getLastNonConfigurationInstance();
      setGraphicalView(
          lastNonConfigurationInstance instanceof PlotBoundaries
              ? (PlotBoundaries) lastNonConfigurationInstance
              : null);

    } catch (ParseException e) {
      Toast.makeText(this, e.getLocalizedMessage(), Toast.LENGTH_LONG).show();
      finish();
    } catch (ArithmeticException e) {
      Toast.makeText(this, e.getLocalizedMessage(), Toast.LENGTH_LONG).show();
      finish();
    }
  }
Exemple #4
0
 public IValue nroot(INumber x, IInteger y) {
   try {
     return x.toReal().nroot(y, values.getPrecision());
   } catch (ArithmeticException ae) {
     throw RuntimeExceptionFactory.arithmeticException(ae.getMessage(), null, null);
   }
 }
Exemple #5
0
 public IValue pow(INumber x, IInteger y) {
   try {
     return x.toReal().pow(y);
   } catch (ArithmeticException ae) {
     throw RuntimeExceptionFactory.arithmeticException(ae.getMessage(), null, null);
   }
 }
 /** Разделить первый аргумент на второй */
 public void divide(double a, double b) {
   try {
     this.result = a / b;
   } catch (ArithmeticException exc) {
     System.out.println(exc.getMessage());
   }
 }
Exemple #7
0
 public IValue log(INumber x, INumber base) {
   try {
     return x.toReal().log(base.toReal(), values.getPrecision());
   } catch (ArithmeticException ae) {
     throw RuntimeExceptionFactory.arithmeticException(ae.getMessage(), null, null);
   }
 }
Exemple #8
0
 public double divide(double a, double b) {
   try {
     return a / b;
   } catch (ArithmeticException exception) {
     System.err.println(exception.getMessage());
   }
   return Double.POSITIVE_INFINITY;
 }
Exemple #9
0
 public int invoke(LuaState luaState) throws LuaRuntimeException {
   try {
     @SuppressWarnings("unused")
     int a = 0 / 0;
   } catch (ArithmeticException e) {
     throw new LuaRuntimeException(e.getMessage(), e);
   }
   return 0;
 }
  public static void main(String[] args) throws Exception {
    // напишите тут ваш код
    try {
      int a = 42 / 0;
    } catch (ArithmeticException e) {
      System.out.println(e.toString());
    }
    // напишите тут ваш код

  }
 public static void tryCatchDummy() throws Throwable {
   try {
     throw new Exception("Dummy exception");
   } catch (ArithmeticException ex) {
     throw new IOException(ex.getMessage());
   } catch (IOException ex) {
     throw new Exception(ex);
   } catch (Exception ex) {
     throw new Exception(ex);
   }
 }
Exemple #12
0
 public IValue scale(INumber x) {
   try {
     if (x.getType().isIntegerType()) {
       IInteger k = (IInteger) x;
       return values.integer(k.toReal().scale());
     }
     if (x.getType().isRationalType()) {
       IRational k = (IRational) x;
       return values.integer(k.toReal().scale());
     }
     return values.integer(((IReal) x).scale());
   } catch (ArithmeticException ae) {
     throw RuntimeExceptionFactory.arithmeticException(ae.getMessage(), null, null);
   }
 }
  private DynamicObject translate(ArithmeticException exception) {
    if (getContext().getOptions().EXCEPTIONS_PRINT_JAVA) {
      exception.printStackTrace();
    }

    return getContext().getCoreLibrary().zeroDivisionError(this);
  }
Exemple #14
0
 public static void main(String[] args) {
   try {
     System.out.println(3 / 0);
     System.out.println("Print me"); // this line not reached
   } catch (ArithmeticException ae) {
     System.out.println("Invalid input...terminating program.....");
     System.out.println(
         "Error :"
             + ae.getMessage()); // if you dont know the reason you can use it to get the error
     // message
   } catch (ArrayIndexOutOfBoundsException aio) {
     System.out.println("Arrya Limits crossed");
   }
   System.out.println("Program Completed");
   System.out.println(5 + 2);
 }
 /**
  * Method for calculating the returns on a given rate path, via the definition for the
  * instantaneous compounded return. u_i = \ln{\frac{S_i}{S_{i-1}}}
  *
  * @return the return, as defined.
  * @exception DemoException thrown if there is a problem with the calculation.
  */
 public ReturnPath getReturnCompounded() throws DemoException {
   if (pathValue == null || nAcceptedPathValue == 0) {
     throw new DemoException("The Rate Path has not been defined!");
   }
   double[] returnPathValue = new double[nAcceptedPathValue];
   returnPathValue[0] = 0.0;
   try {
     for (int i = 1; i < nAcceptedPathValue; i++) {
       returnPathValue[i] = Math.log(pathValue[i] / pathValue[i - 1]);
     }
   } catch (ArithmeticException aex) {
     throw new DemoException("Error in getReturnLogarithm:" + aex.toString());
   }
   ReturnPath rPath = new ReturnPath(returnPathValue, nAcceptedPathValue, ReturnPath.COMPOUNDED);
   //
   // Copy the PathId information to the ReturnPath object.
   rPath.copyInstanceVariables(this);
   rPath.estimatePath();
   return (rPath);
 }
  public static void main(String args[]) {
    Scanner teclado = new Scanner(System.in);

    System.out.print("Digite o numerador: ");
    String xs = teclado.nextLine();

    System.out.print("Digite o denominador: ");
    String ys = teclado.nextLine();

    teclado.close();

    int x = Integer.parseInt(xs), y = Integer.parseInt(ys);

    try {
      int divisao = divide(x, y);
      System.out.println("Resultado da divisao: " + divisao);
    } catch (ArithmeticException erro) {
      System.err.println("Erro: " + erro.getMessage());
    }
  }
Exemple #17
0
  public Function(String formula, ViewPort port, double step) {
    this.formula = formula;
    this.xmin = BigDecimal.valueOf(port.get_xmin());
    this.xmax = BigDecimal.valueOf(port.get_xmax());

    Parser parser = new Parser();
    BigDecimal run = xmin;
    while (run.compareTo(xmax) <= 0) {
      try {
        this.add_valuepair(run, parser.parse_x(formula, String.valueOf(run)));
        run = run.add(BigDecimal.valueOf(step));
      } catch (ArithmeticException e) {
        run = run.add(BigDecimal.valueOf(step));
        System.out.println(
            "Arithmetik Exception wahrscheinlich Division durch 0 übersprungen."
                + e.getMessage()
                + e.getLocalizedMessage());
        continue;
      }
    }
  }
Exemple #18
0
  protected static void validateRowOfLongs(String messagePrefix, VoltTable vt, long[] expected) {
    int len = expected.length;
    assertTrue(vt.advanceRow());
    for (int i = 0; i < len; i++) {
      String message = messagePrefix + "at column " + i + ", ";

      long actual = -10000000;
      // ENG-4295: hsql bug: HSQLBackend sometimes returns wrong column type.
      try {
        actual = vt.getLong(i);
      } catch (IllegalArgumentException ex) {
        try {
          actual = (long) vt.getDouble(i);
        } catch (IllegalArgumentException newEx) {
          try {
            actual = vt.getTimestampAsLong(i);
          } catch (IllegalArgumentException exTm) {
            try {
              actual = vt.getDecimalAsBigDecimal(i).longValueExact();
            } catch (IllegalArgumentException newerEx) {
              newerEx.printStackTrace();
              fail(message);
            }
          } catch (ArithmeticException newestEx) {
            newestEx.printStackTrace();
            fail(message);
          }
        }
      }

      // Long.MIN_VALUE is like a NULL
      if (expected[i] != Long.MIN_VALUE) {
        assertEquals(message, expected[i], actual);
      } else {
        VoltType type = vt.getColumnType(i);
        assertEquals(
            message + "expected null: ", Long.parseLong(type.getNullValue().toString()), actual);
      }
    }
  }
Exemple #19
0
 /**
  * Evaluates this binary add arithmetic function.
  *
  * @return the result of the evaluation.
  * @throws EvaluationException if the function is not evaluable or if an arithmetic error occurs
  *     during the evaluation.
  * @see pddl4j.exp.fexp.OpExp#isEvaluable()
  */
 public Number evaluate() throws EvaluationException {
   if (!this.isGround())
     throw new EvaluationException("arithmetic function " + this.toString() + " not ground");
   try {
     Number arg1 = null;
     if (this.getArg1().getTermID().equals(TermID.ARITHMETIC_FUNCTION)) {
       OpExp func = (OpExp) this.getArg1();
       arg1 = func.evaluate();
     } else if (this.getArg1().getTermID().equals(TermID.NUMBER)) {
       arg1 = (Number) this.getArg1();
     } else {
       throw new EvaluationException(
           "arithmetic function "
               + this.toString()
               + ": argument "
               + this.getArg1()
               + " is not evaluable");
     }
     Number arg2 = null;
     if (this.getArg2().getTermID().equals(TermID.ARITHMETIC_FUNCTION)) {
       OpExp func = (OpExp) this.getArg2();
       arg2 = func.evaluate();
     } else if (this.getArg2().getTermID().equals(TermID.NUMBER)) {
       arg2 = (Number) this.getArg2();
     } else {
       throw new EvaluationException(
           "arithmetic function "
               + this.toString()
               + ": argument "
               + this.getArg2()
               + " is not evaluable");
     }
     return new Number(arg1.getValue() + arg2.getValue());
   } catch (ArithmeticException e) {
     throw new EvaluationException(
         "arithmetic function " + this.toString() + ": " + e.getMessage(), e);
   }
 }
Exemple #20
0
  // test client
  public static void main(String[] args) {

    try {
      test1();
    } catch (ArithmeticException e) {
      e.printStackTrace();
    }
    System.out.println("--------------------------------");

    try {
      test2();
    } catch (ArithmeticException e) {
      e.printStackTrace();
    }
    System.out.println("--------------------------------");

    try {
      test3();
    } catch (ArithmeticException e) {
      e.printStackTrace();
    }
    System.out.println("--------------------------------");

    try {
      test4();
    } catch (ArithmeticException e) {
      e.printStackTrace();
    }
    System.out.println("--------------------------------");

    int M = Integer.parseInt(args[0]);
    int N = Integer.parseInt(args[1]);
    double[] c = new double[N];
    double[] b = new double[M];
    double[][] A = new double[M][N];
    for (int j = 0; j < N; j++) c[j] = Math.random() * 1000;
    for (int i = 0; i < M; i++) b[i] = Math.random() * 1000;
    for (int i = 0; i < M; i++) for (int j = 0; j < N; j++) A[i][j] = Math.random() * 1000;
    Simplex lp = new Simplex(A, b, c);
    System.out.println(lp.value());
  }
 @Override
 public final Object eval() throws ArithmeticException {
   FunctionsDefinitions def = FunctionsDefinitions.getInstance();
   Function function = def.getFunction(key);
   if (function == null) {
     throw new ArithmeticException(
         "Function " + key.getName() + "( " + key.getParamsSize() + " parameters) does not exist");
   } else {
     Method method = function.getMethod();
     if (fields == null) {
       initFieldsArray(function, method);
     }
     Object obj = function.getObject();
     if (varargs) {
       Class clazz = method.getParameterTypes()[fields.length - 1];
       Class ctype = getVarargType(clazz);
       if (ctype == Integer.TYPE) {
         fillIntField(fields);
       } else if (ctype == Float.TYPE) {
         fillFloatField(fields);
       } else {
         fillObjectField(fields);
       }
     } else {
       for (int i = 0; i < exprs.size(); i++) {
         Expression expr = exprs.get(i);
         Object _f = null;
         if (expr.getResultType() == TYPE_INTEGER) {
           _f = getField(expr.evalAsInt(), method.getParameterTypes()[i]);
         } else if (expr.getResultType() == TYPE_FLOAT) {
           _f = getField(expr.evalAsFloat(), method.getParameterTypes()[i]);
         } else if (expr.getResultType() == TYPE_BOOL) {
           _f = getField(expr.evalAsBoolean(), method.getParameterTypes()[i]);
         } else {
           _f = getField(expr.eval(), method.getParameterTypes()[i]);
         }
         fields[i] = _f;
       }
     }
     try {
       Object result = null;
       if (varargs) {
         result = method.invoke(obj, fields);
       } else {
         result = method.invoke(obj, fields);
       }
       if (method.getReturnType() == Integer.TYPE) {
         return result;
       } else if (method.getReturnType() == Short.TYPE) {
         return ((Short) result).intValue();
       } else if (method.getReturnType() == Double.TYPE) {
         return ((Double) result).floatValue();
       } else if (method.getReturnType() == Float.TYPE) {
         Float f = (Float) result;
         if (f.isInfinite()) {
           throw newArithmeticException(function);
         }
         return f;
       } else if (method.getReturnType() == Boolean.TYPE) {
         return ((Boolean) result).booleanValue();
       } else {
         return result;
       }
     } catch (IllegalAccessException ex) {
       ArithmeticException e =
           new ArithmeticException("IllegalAccessException for function " + function.getName());
       throw e;
     } catch (IllegalArgumentException ex) {
       ArithmeticException e =
           new ArithmeticException("Illegal argument for function " + function.getName());
       throw e;
     } catch (InvocationTargetException ex) {
       Throwable _ex = ex.getCause();
       String message = null;
       if (_ex != null) {
         message = "Exception in function " + function.getName() + " (" + _ex.getMessage() + ")";
       } else {
         message = "Exception in function " + function.getName();
       }
       ArithmeticException e = new ArithmeticException(message);
       e.initCause(_ex);
       e.setStackTrace(_ex.getStackTrace());
       throw e;
     }
   }
 }
Exemple #22
0
  public static void main(String[] args) {

    int a = 1;
    int b = 0;
    int c = 0;

    try {
      c = 7; // 7a / b; // EXCEPTION OCCURS - LEAVE THE BLOCK
      System.out.println("Bill rocks!");
      System.out.println("WOOOO");
    } catch (Exception ex) {
      System.out.println("You broke the universe!");
      // return;
      System.exit(0);
    } finally {
      System.out.println("FINALLY - La la la!");
    }

    System.out.println("After the block!");

    try {
      Thread.sleep(2);
    } catch (InterruptedException iex) {
      System.out.println("Thread, Interrupted.");
    }
    System.out.println("...");

    // If you want to "catch" an exception (not throw
    // it up to be handled by whoever called this method,
    // you can wrap it in a try..catch block.

    // The try block is the code that will be executed.
    // If an exception occurs, this block will cease
    // execution and the exception will be thrown.  However, it
    // will then be caught by the catch block, and the catch
    // block will execute.

    //

    // In this case, when we divide by zero,

    try {
      c = a / b;
      // Lots of code...
    } catch (ArithmeticException aex) {
      System.out.println(aex.toString());
    }

    // Note that having something in a try block does not mean
    // that an exception will or can occur!  Nothing is stopping
    // you from doing this.

    try {
      c = 8 * 2;
    } catch (ArithmeticException aex) {
      System.out.println("This will never be called!");
      System.out.println(aex.toString());
    }

    // You ordinarily want to be as specific as possible when
    // saying what exception might be thrown, but you can also
    // use the superclass Exception to catch ANY exception.

    // This is polymorphism in action!

    try {
      c = 17 / 0;
    } catch (Exception ex) {
      System.out.println("Exception = ");
      System.out.println(ex.toString());
    }

    // What if multiple exceptions can occur?  One way, of course,
    // is to simply catch Exception.  What if you wanted to do different
    // things depending on exception?  For example, if you can't
    // read from a file or the file is corrupt, you might want to
    // display different error messages to a user.  In that case, you
    // can have multiple catch blocks, one for each exception.

    // Remember that the code in the block will stop executing as soon as
    // an exception is hit!

    try {
      int[] d = new int[5];
      int e = 70;

      d[e] = 18;
      c = a / b;
    } catch (ArithmeticException aex) {
      System.out.println("You can't divide by zero!");
      System.out.println(aex.toString());
    } catch (ArrayIndexOutOfBoundsException obex) {
      System.out.println("You can't access out-of-bounds array indexes!");
      System.out.println(obex.toString());
    }

    // Exceptions are handled from top to bottom - so put most specific errors
    // on top, then move down to less specific!

    // THIS IS BAD!  In fact, Java 1.8 won't even let you do it.

    // try {
    //     c = a / b;
    // } catch (Exception obex) {
    //     System.out.println("Something happened, I don't know what!");
    //     System.out.println(obex.toString());
    // } catch (ArithmeticException aex) {
    //     System.out.println("You can't divide by zero!");
    //     System.out.println(aex.toString());
    // }

    // THIS IS BETTER!

    try {
      c = a / b;
    } catch (ArithmeticException aex) {
      System.out.println("You can't divide by zero!");
      System.out.println(aex.toString());
    } catch (Exception obex) {
      System.out.println("Something happened, I don't know what!");
      System.out.println(obex.toString());
    }

    // What happens if an exception occurs INSIDE a catch block?

    // You're no longer in a try block, so nothing will save you!  The exception is
    // thrown and since nothing catches it, the program will halt.

    // For this reason, be very careful what you do in the catch block.

    try {
      c = 12 / 0;
    } catch (ArithmeticException aex) {
      System.out.println("You can't divide 12 / 0!  Watch:");
      // try {
      // c = 12 / 0;
      // } catch (Exception ex) {
      // }
    }

    // Sometimes you want to do something at the END of a try block,
    // if an exception occurs or not.  For this, you can use finally.

    // A finally block goes at the end of the catch blocks, and is executed
    // after the try block finished (remember it can finish early!) and any
    // caught exceptions occur.

    int[] g = new int[17];

    try {
      int sum = 0;
      for (int j = 0; j <= g.length; j++) {
        g[j] = j;
        sum += j;
      }
      System.out.println("Sum is " + sum);
    } catch (Exception ex) {
      System.out.println("Could not sum!  Had an error occur!");
    } finally {
      System.out.println("Resetting g...");
      for (int j = 0; j < g.length; j++) {
        g[j] = 0;
      }
    }

    // Although tracking down the error may seem simple, it gets difficult for
    // larger programs where the location where the error is caught may be very
    // different than where it is thrown.

    // .printStackTrace lets us see a "trace" of the stack, to see where the error
    // actually occurred and what called it.

    try {
      int x = laboonify(17);
      System.out.println("17 laboonified is " + x);
    } catch (Exception ex) {
      System.out.println("Could not laboonify 17!");
      // Hard to determine where the error is just with this!
      System.out.println(ex.toString());
      // Note that this does the printing for you - it does not return
      // a String, so no need to println() it.
      ex.printStackTrace();
    }
  }
Exemple #23
0
  // ======================================================================
  // [FUNC] Accepts input key from the user.
  public void inputKey(String key) {
    if (hasError) {
      if (key == CXX || key == GRP) {
      } else if (key == HEX || key == DEC || key == OCT || key == BIN) initFields();
      else {
        beep();
        return;
      }
    } else if (lastKey == EQU && key != BSP) {
      clear();
    }

    switch (key) {
      case GRP:
        groupDigits = !groupDigits;
        if (hasError) return;
        break;
      case BIN:
      case OCT:
      case DEC:
      case HEX:
        prmScreenText = dec2rad(rad2dec(prmScreenText, numMode), key);
        numMode = key;
        clearPrmScreen = true;
        break;
      case MCX:
        memValue = "0";
        clearPrmScreen = true;
        break;
      case MRX:
        if (memValue != "0") prmScreenText = dec2rad(memValue, numMode);
        else {
          prmScreenText = "0";
          lastKey = DG0;
          return;
        }
        clearPrmScreen = true;
        break;
      case MSX:
        memValue = rad2dec(prmScreenText, numMode);
        clearPrmScreen = true;
        break;
      case MPX:
        memValue =
            new BigDecimal(rad2dec(prmScreenText, numMode))
                .add(new BigDecimal(memValue))
                .toPlainString();
        clearPrmScreen = true;
        break;
      case MMX:
        memValue =
            new BigDecimal(rad2dec(memValue, numMode))
                .subtract(new BigDecimal(prmScreenText))
                .toPlainString();
        clearPrmScreen = true;
        break;
      case BSP:
        if (clearPrmScreen) {
          beep();
          return;
        } else if (prmScreenText.length() > 1)
          prmScreenText = prmScreenText.substring(0, prmScreenText.length() - 1);
        else if (prmScreenText != "0") prmScreenText = "0";
        else if (expr[0].hasItems()) pop();
        else beep();
        break;
      case CEX:
        prmScreenText = "0";
        break;
      case CXX:
        this.initFields();
        break;
      case AVG:
        if (nset.size() > 0) {
          BigDecimal bd = BigDecimal.ZERO;
          for (int i = 0; i < nset.size(); i++) bd = bd.add((BigDecimal) nset.get(i));
          prmScreenText =
              dec2rad(
                  bd.divide(new BigDecimal(nset.size()), 32, BigDecimal.ROUND_HALF_EVEN)
                      .stripTrailingZeros()
                      .toPlainString(),
                  numMode);
        } else throwError("Invalid Operation: Empty set");
        clearPrmScreen = true;
        break;
      case SUM:
        BigDecimal bd = BigDecimal.ZERO;
        for (int i = 0; i < nset.size(); i++) bd = bd.add((BigDecimal) nset.get(i));
        prmScreenText = dec2rad(bd.toPlainString(), numMode);
        clearPrmScreen = true;
        if (prmScreenText == "0") {
          lastKey = DG0;
          return;
        }
        break;
      case LST:
        if (prmScreenText != "0") nset.add(new BigDecimal(rad2dec(prmScreenText, numMode)));
        else beep();
        clearPrmScreen = true;
        break;
      case CLS:
        nset.clear();
        break;
      case DG0:
        if (clearPrmScreen) {
          prmScreenText = "0";
          clearPrmScreen = false;
        } else if (prmScreenText != "0") prmScreenText += key;
        else if (lastKey == DG0) beep();
        break;
      case DG1:
      case DG2:
      case DG3:
      case DG4:
      case DG5:
      case DG6:
      case DG7:
      case DG8:
      case DG9:
      case DGA:
      case DGB:
      case DGC:
      case DGD:
      case DGE:
      case DGF:
        if (clearPrmScreen || prmScreenText == DG0) {
          prmScreenText = key;
          clearPrmScreen = false;
        } else prmScreenText += key;
        break;
      case DOT:
        if (clearPrmScreen || prmScreenText == DG0) {
          prmScreenText = DG0 + DOT;
          clearPrmScreen = false;
        } else if (prmScreenText.indexOf(DOT) < 0) prmScreenText += key;
        else beep();
        break;
      case BR1:
      case BR2:
      case SRT:
      case CRT:
      case REC:
      case SQR:
      case CUB:
      case FCT:
      case SIN:
      case COS:
      case TAN:
      case LOG:
      case NLG:
      case INT:
      case NEG:
      case POW:
      case MUL:
      case DIV:
      case MOD:
      case ADD:
      case SUB:
        if (prmScreenText != "0" || isDigit(lastKey)) push(prmScreenText);
        if (key.equals(BR1)) push(Expression.BRO);
        else if (key.equals(BR2)) push(Expression.BRC);
        else if (key.equals(SRT)) push(Expression.SRT);
        else if (key.equals(CRT)) push(Expression.CRT);
        else if (key.equals(REC)) push(Expression.REC);
        else if (key.equals(SQR)) push(Expression.SQR);
        else if (key.equals(CUB)) push(Expression.CUB);
        else if (key.equals(FCT)) push(Expression.FCT);
        else if (key.equals(SIN)) push(Expression.SIN);
        else if (key.equals(COS)) push(Expression.COS);
        else if (key.equals(TAN)) push(Expression.TAN);
        else if (key.equals(LOG)) push(Expression.LOG);
        else if (key.equals(NLG)) push(Expression.NLG);
        else if (key.equals(INT)) push(Expression.INT);
        else if (key.equals(NEG)) push(Expression.NEG);
        else if (key.equals(POW)) push(Expression.POW);
        else if (key.equals(MUL)) push(Expression.MUL);
        else if (key.equals(DIV)) push(Expression.DIV);
        else if (key.equals(MOD)) push(Expression.MOD);
        else if (key.equals(ADD)) push(Expression.ADD);
        else if (key.equals(SUB)) push(Expression.SUB);
        prmScreenText = "0";
        clearPrmScreen = false;
        break;
      case EQU:
        if (prmScreenText != "0" || isDigit(lastKey) || !expr[0].hasItems()) push(prmScreenText);
        try {
          prmScreenText = stripZeros(expr[0].eval().toPlainString());
          if (numMode == BIN) prmScreenText = dec2rad(prmScreenText, BIN);
          else if (numMode == OCT) prmScreenText = dec2rad(prmScreenText, OCT);
          else if (numMode == HEX) prmScreenText = dec2rad(prmScreenText, HEX);
          clearPrmScreen = true;
        } catch (SyntaxErrorException e) {
          throwError("Syntax Error: " + e.getMessage());
        } catch (InvalidInputException e) {
          throwError("Input Error: " + e.getMessage());
        } catch (UnknownOperatorException e) {
          throwError("Unknown Operator: " + e.getMessage());
        } catch (ArithmeticException e) {
          throwError("Math Error: " + e.getMessage());
        } catch (Exception e) {
          throwError("Application Error: " + e.getMessage());
        }
        break;
    }

    lastKey = key;
  }
  private static Map<String, ExchangeRate> requestExchangeRates(
      final URL url,
      float dogeBtcConversion,
      final String userAgent,
      final String source,
      final String... fields) {
    final long start = System.currentTimeMillis();

    HttpURLConnection connection = null;
    Reader reader = null;

    try {
      connection = (HttpURLConnection) url.openConnection();

      connection.setInstanceFollowRedirects(false);
      connection.setConnectTimeout(Constants.HTTP_TIMEOUT_MS);
      connection.setReadTimeout(Constants.HTTP_TIMEOUT_MS);
      connection.addRequestProperty("User-Agent", userAgent);
      connection.addRequestProperty("Accept-Encoding", "gzip");
      connection.connect();

      final int responseCode = connection.getResponseCode();
      if (responseCode == HttpURLConnection.HTTP_OK) {
        final String contentEncoding = connection.getContentEncoding();

        InputStream is = new BufferedInputStream(connection.getInputStream(), 1024);
        if ("gzip".equalsIgnoreCase(contentEncoding)) is = new GZIPInputStream(is);

        reader = new InputStreamReader(is, Constants.UTF_8);
        final StringBuilder content = new StringBuilder();
        final long length = Io.copy(reader, content);

        final Map<String, ExchangeRate> rates = new TreeMap<String, ExchangeRate>();

        final JSONObject head = new JSONObject(content.toString());
        for (final Iterator<String> i = head.keys(); i.hasNext(); ) {
          final String currencyCode = i.next();
          if (!"timestamp".equals(currencyCode)) {
            final JSONObject o = head.getJSONObject(currencyCode);

            for (final String field : fields) {
              final String rate = o.optString(field, null);

              if (rate != null) {
                try {
                  BigDecimal btcRate = new BigDecimal(GenericUtils.toNanoCoins(rate, 0));
                  BigInteger dogeRate =
                      btcRate.multiply(BigDecimal.valueOf(dogeBtcConversion)).toBigInteger();

                  if (dogeRate.signum() > 0) {
                    rates.put(currencyCode, new ExchangeRate(currencyCode, dogeRate, source));
                    break;
                  }
                } catch (final ArithmeticException x) {
                  log.warn(
                      "problem fetching {} exchange rate from {} ({}): {}",
                      currencyCode,
                      url,
                      contentEncoding,
                      x.getMessage());
                }
              }
            }
          }
        }

        log.info(
            "fetched exchange rates from {} ({}), {} chars, took {} ms",
            url,
            contentEncoding,
            length,
            System.currentTimeMillis() - start);

        return rates;
      } else {
        log.warn("http status {} when fetching {}", responseCode, url);
      }
    } catch (final Exception x) {
      log.warn("problem fetching exchange rates from " + url, x);
    } finally {
      if (reader != null) {
        try {
          reader.close();
        } catch (final IOException x) {
          // swallow
        }
      }

      if (connection != null) connection.disconnect();
    }

    return null;
  }