Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // 63180383
- abstract class Izraz {
- public static void main(String[] args) {
- Izraz x = Izraz.zgradi("3+4");
- System.out.println(x.steviloOperatorjev());
- }
- public static Izraz zgradi(String niz) {
- int I = 0;
- int J = niz.length() - 1;
- while (1 == 1) {
- int zag = 0;
- boolean cc = true;
- if (niz.charAt(I) == '(' && niz.charAt(J) == ')') {
- for (int i = I + 1; i < J; i++) {
- if (niz.charAt(i) == '(')
- zag++;
- else if(niz.charAt(i) == ')')
- zag--;
- if (zag < 0) {
- cc = false;
- break;
- }
- }
- }
- else {
- cc = false;
- }
- if (zag != 0)
- cc = false;
- if (cc == true) {
- I++;
- J--;
- }
- if (I >= J) {
- I--;
- J++;
- break;
- }
- }
- String nniz = niz.substring(I, J + 1);
- char a = 'a';
- int index = -1;
- for (int i = nniz.length() - 1; i > 0; i--) {
- int zag = 0;
- if (nniz.charAt(i) == '/' || nniz.charAt(i) == '*' || nniz.charAt(i) == '+' || nniz.charAt(i) == '-') {
- if (a == 'a') {
- a = nniz.charAt(i);
- }
- else if (a != nniz.charAt(i))
- continue;
- for (int j = 0; j < i; j++) {
- if (nniz.charAt(j) == '(')
- zag++;
- else if(nniz.charAt(j) == ')')
- zag--;
- if (zag < 0)
- break;
- }
- if (zag != 0)
- continue;
- zag = 0;
- for (int j = i + 1; j < nniz.length(); j++) {
- if (nniz.charAt(j) == '(')
- zag++;
- else if(nniz.charAt(j) == ')')
- zag--;
- if (zag < 0)
- break;
- }
- if (zag != 0)
- continue;
- else {
- index = i;
- break;
- }
- }
- }
- if (index == -1) {
- return new Stevilo (Integer.valueOf(nniz));
- }
- return new SestavljeniIzraz(zgradi(nniz.substring(0, index)), nniz.charAt(index), zgradi(nniz.substring(index + 1, nniz.length())));
- }
- public int steviloOperatorjev() {
- if (this instanceof Stevilo) return 0;
- return 1 + ((SestavljeniIzraz) this).left.steviloOperatorjev() + ((SestavljeniIzraz) this).right.steviloOperatorjev();
- }
- public String postfiksno() {
- if (this instanceof Stevilo) return Integer.toString(((Stevilo) this).value);
- return ((SestavljeniIzraz) this).left.postfiksno() + ((SestavljeniIzraz) this).right.postfiksno() + Character.toString(((SestavljeniIzraz) this).op);
- }
- public int vrednost() {
- if (this instanceof Stevilo) return ((Stevilo) this).value;
- char ch = ((SestavljeniIzraz) this).op;
- int left = ((SestavljeniIzraz) this).left.vrednost();
- int right = ((SestavljeniIzraz) this).right.vrednost();
- if (ch == '+') return left + right;
- if (ch == '-') return left - right;
- if (ch == '*') return left * right;
- if (ch == '/') return left / right;
- return -1;
- return -1;
- }
- }
- class Stevilo extends Izraz {
- int value;
- public Stevilo(int n) {
- this.value = n;
- }
- }
- class SestavljeniIzraz extends Izraz {
- char op;
- Izraz left, right;
- public SestavljeniIzraz(Izraz levi, char operator, Izraz desni) {
- this.left = levi;
- this.right = desni;
- this.op = operator;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement