Write comment lines on each line of code. java 5. Problem Statement Create an in
ID: 3856342 • Letter: W
Question
Write comment lines on each line of code.
java
Explanation / Answer
package myPack;
/**
*
* @author Sam
*/
interface Stack {
void push(int i);
int pop();
}
class FixedStack implements Stack{
private final int arr[];
private final int size;
private int top;
public FixedStack(int size) {
this.size = size;
arr = new int[size];
top = -1;
}
@Override
public void push(int i) {
if (top == size - 1) {
System.out.println("Stack overflow while pushing " + i + " in fixed stack");
//throw new UnsupportedOperationException();
return;
}
arr[++top] = i;
}
@Override
public int pop() {
if (top < 0) {
System.out.println("Stack underflow");
//throw new UnsupportedOperationException();
return -999;
}
return arr[top --];
}
}
class VariableStack implements Stack{
int arr[];
int size;
int top;
public VariableStack(int size) {
this.size = size;
arr = new int[size];
top = -1;
}
@Override
public void push(int i) {
if (top == size - 1) {
realloc();
}
arr[++top] = i;
}
@Override
public int pop() {
if (top < 0) {
System.out.println("Stack underflow");
//throw new UnsupportedOperationException();
return -999;
}
return arr[top --];
}
private void realloc() {
int tmpArr[] = new int[size*2];
System.arraycopy(arr, 0, tmpArr, 0, size);
size *= 2;
arr = tmpArr;
}
}
public class TestClass {
public static void main(String[] args) {
FixedStack fs = new FixedStack(3);
fs.push(1);
fs.push(2);
fs.push(3);
//ERROR
fs.push(0);
VariableStack vs = new VariableStack(3);
vs.push(1);
vs.push(2);
vs.push(3);
vs.push(0);
vs.push(9);
//no error
}
}
I hope you like it. Let me know your views
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.