This commit is contained in:
2022-10-26 11:13:11 +02:00
parent 768f122da4
commit ca5a8516fd
15 changed files with 409 additions and 4 deletions

View File

@@ -0,0 +1,44 @@
public class Arithmetique {
public static void main(String[] args) {
ArrayPile<Integer> pile = new ArrayPile<>();
for (String arg : args) {
try {
int n = Integer.parseInt(arg);
pile.addFirst(n);
} catch (NumberFormatException e) {
if (pile.size() < 2) {
System.err.println("Invalid stack size.");
return;
}
int n2 = pile.pollFirst();
int n1 = pile.pollFirst();
switch (arg) {
case "+":
pile.addFirst(n1 + n2);
break;
case "-":
pile.addFirst(n1 - n2);
break;
case "/":
pile.addFirst(n1 / n2);
break;
case "x":
pile.addFirst(n1 * n2);
break;
default:
System.err.println("Invalid operator");
return;
}
}
}
System.out.println(pile.pollFirst());
}
}

View File

@@ -0,0 +1,55 @@
public class ArrayPile<E> implements Pile<E>{
int size = 16;
int currentElement = 0;
E[] table;
public ArrayPile() {
table = (E[])new Object[size];
};
private void resizeStack() {
size *= 2;
E[] newTable = (E[])new Object[size];
for (int i = 0; i < table.length; i++) {
newTable[i] = table[i];
}
table = newTable;
}
@Override
public E getFirst() {
if (currentElement == 0) {
return null;
} else {
return table[currentElement-1];
}
}
@Override
public E pollFirst() {
if (currentElement == 0) {
return null;
} else {
E e = table[currentElement-1];
currentElement--;
return e;
}
}
@Override
public void addFirst(E e) {
if (currentElement >= table.length) resizeStack();
table[currentElement] = e;
currentElement++;
}
@Override
public int size() {
return currentElement;
}
}

View File

@@ -0,0 +1,6 @@
public interface Pile<E> {
public E getFirst();
public E pollFirst();
public void addFirst(E e);
public int size();
}