Im having trouble with my stack program and I don't really understand my errors. Can I please get some help? Every time i try to run it, it has multiple errors and im extremely confused on a few things. the errors i have is a total of 60 errors. therefore the whole program is off. All im trying to do is to create names in this stack and queue program.
public class YourStackNB {
private int maxSize;
private long[] stackArray;
private int top;
public YourStackNB(int s) {
maxSize = s;
stackArray = new long[maxSize];
top = -1;
}
public void push(long j) {
stackArray[++top] = j;}
public long pop() {
return stackArray[top--];
}
public boolean isEmpty() {
return (top == -1);
}
public static void main(String[] args) {
YourStackNB theStack = new YourStackNB();
Stack<Name> even = new Stack<>();
theStack.push(dino);
theStack.push(perry);
theStack.push(jada);
theStack.push(holly);
theStack.push(nori);
while (!theStack.isEmpty()) {
long value = theStack.pop();
System.out.print(value);
System.out.print(" ");
}
System.out.println("");
}
}
You are trying to implement stack using array. But you are not using it properly. Rather you are trying to use java.util.Stack with passing incorrect type Name.
Another thing you are trying to implement Stack of long data type. But you are trying to put some string there. These codes are incorrect
// Stack<Name> even = new Stack<>();
// theStack.push(dino);
// theStack.push(perry);
// theStack.push(jada);
// theStack.push(holly);
// theStack.push(nori);
I can suggest you please try to write some basic java program so that you are more aware of java syntax and it will help you to better thinking.
Just for your learning I am fixing the errors and this code can be implemented in better way
public class YourStackNB {
private int maxSize;
private long[] stackArray;
private int top;
public YourStackNB(int s) {
maxSize = s;
stackArray = new long[maxSize];
top = -1;
}
public void push(long j) {
stackArray[++top] = j;}
public long pop() {
return stackArray[top--];
}
public boolean isEmpty() {
return (top == -1);
}
public static void main(String[] args) {
YourStackNB theStack = new YourStackNB(10);
theStack.push(100);
theStack.push(200);
theStack.push(300);
theStack.push(400);
theStack.push(500);
// Stack<Name> even = new Stack<>();
// theStack.push(dino);
// theStack.push(perry);
// theStack.push(jada);
// theStack.push(holly);
// theStack.push(nori);
while (!theStack.isEmpty()) {
long value = theStack.pop();
System.out.print(value);
System.out.print(" ");
}
System.out.println("");
}
}
OUTPUT: 500 400 300 200 100
As stack is last in first out(LIFO) thus it's printing in reverse order we inserted the element into it.