Add 3 1b) (Int Stack)

This commit is contained in:
Matti 2024-05-09 20:17:21 +02:00
parent f829b973eb
commit 12b7b279c0
3 changed files with 93 additions and 11 deletions

View File

@ -20,19 +20,39 @@ package part3.aufg1;
*/
public class Anwendung {
public static void main(String[] args){
public void myIntStackDemo(){
IntStack myIntStack = new IntStack();
myIntStack.push(7);myIntStack.print();
myIntStack.push(3);myIntStack.print();
myIntStack.push(8);myIntStack.print();
myIntStack.push(2);myIntStack.print();
myIntStack.p_push(7);
myIntStack.p_push(3);
myIntStack.p_push(8);
myIntStack.p_push(2);
myIntStack.pop();myIntStack.print();
myIntStack.pop();myIntStack.print();
myIntStack.p_pop();
myIntStack.p_pop();
myIntStack.push(7);myIntStack.print();
myIntStack.p_push(7);
myIntStack.pop();myIntStack.print();
myIntStack.pop();myIntStack.print();
myIntStack.p_pop();
myIntStack.p_pop();
myIntStack.p_pop();
}
public void myGenericStackDemo(){
GenericStack myStack = new GenericStack();
myStack.p_push(1);
myStack.p_push('B');
myStack.p_push(true);
myStack.p_pop();
myStack.p_push("\"Ich Liebe Generische Typen\"");
}
public static void main(String[] args){
Anwendung demo = new Anwendung();
demo.myIntStackDemo();
System.out.println("=====/////======");
demo.myGenericStackDemo();
}
}

View File

@ -0,0 +1,51 @@
package part3.aufg1;
import java.util.Arrays;
public class GenericStack<T> {
Object[] myArray;
private int MAX_SIZE;
private int firstFreeIndex;
public GenericStack(){
this.MAX_SIZE = 100;
this.firstFreeIndex = 0;
this.myArray = new Object[MAX_SIZE];
}
public void push(T t){
this.myArray[this.firstFreeIndex] = t;
this.firstFreeIndex++;
}
public void p_push(T t){
this.push(t);
this.print();
}
public T pop(){
return (T) this.myArray[--this.firstFreeIndex];
}
public T p_pop(){
T temp = this.pop();
this.print();
return temp;
}
public Object[] toArray(){
if (this.firstFreeIndex<1){
return new Object[0];
}
Object[] retArray = new Object[this.firstFreeIndex];
for (int i=0; i<firstFreeIndex; i++){
retArray[i] = this.myArray[i];
}
return retArray;
}
public void print(){
System.out.println(Arrays.toString(this.toArray()));
}
}

View File

@ -18,13 +18,24 @@ public class IntStack {
this.firstFreeIndex++;
}
public void p_push(int value){
this.push(value);
this.print();
}
public int pop(){
return this.myArray[--this.firstFreeIndex];
}
public int p_pop(){
int temp = this.pop();
this.print();
return temp;
}
public int[] toArray(){
if (firstFreeIndex<1){
return null;
return new int[0];
}
int[] retArray = new int[firstFreeIndex];
for (int i=0; i<firstFreeIndex; i++){