Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.io.BufferedReader;
- import java.io.IOException;
- import java.io.InputStreamReader;
- /**
- * @author Jan Buchar
- */
- public class CodEx
- {
- private static String line;
- private static int cursor;
- public static void main (String[] args)
- {
- BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
- try {
- while ((line = reader.readLine()) != null) {
- if (isEmpty(line)) {
- continue;
- }
- try {
- System.out.printf("%.5f\n", eval(line));
- } catch (Exception e) {
- System.out.println("ERROR");
- }
- }
- } catch (IOException e) {
- System.out.println("ERROR");
- }
- }
- private static boolean isEmpty (String line)
- {
- for (char ch: line.toCharArray()) {
- if (!Character.isWhitespace(ch)) {
- return false;
- }
- }
- return true;
- }
- private static void next ()
- {
- do {
- cursor++;
- } while (current() != 0 && Character.isWhitespace(current()));
- }
- private static char current ()
- {
- if (cursor >= line.length()) {
- return 0;
- }
- return line.charAt(cursor);
- }
- private static double eval (String line) throws Exception
- {
- cursor = -1;
- next();
- return sub();
- }
- private static double sub () throws Exception
- {
- double result = add();
- while (current() == '-') {
- next();
- result -= add();
- }
- return result;
- }
- private static double add () throws Exception
- {
- double result = div();
- while (current() == '+') {
- next();
- result += div();
- }
- return result;
- }
- private static double div () throws Exception
- {
- double result = mul();
- while (current() == '/') {
- next();
- result /= mul();
- }
- return result;
- }
- private static double mul () throws Exception
- {
- double result = val();
- while (current() == '*') {
- next();
- result *= val();
- }
- return result;
- }
- private static double val () throws Exception
- {
- if (current() == '(') {
- next();
- double result = sub();
- if (current() != ')') {
- throw new Exception();
- }
- next();
- return result;
- }
- StringBuilder builder = new StringBuilder();
- do {
- builder.append(current());
- cursor++;
- } while (current() != '+'
- && current() != '-'
- && current() != '*'
- && current() != '/'
- && current() != '('
- && current() != ')'
- && current() != 0
- );
- String number = builder.toString();
- if (isEmpty(number)) {
- throw new Exception();
- }
- try {
- return Double.parseDouble(number);
- } catch (NumberFormatException e) {
- throw new Exception();
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement