Not displaying elements from stack - java

So I have written this JAVA-program for stack and the problem is I cant display the elements using the display() method which I used in the code.
here is my Stack class.
public class Stack {
//members
private int top;
private int size;
private int[] a;
private int i;
//constructor
public Stack() {
this.top = -1;
this.size = 5;
this.a = new int[size];
}
private boolean isempty() {
if(top == -1) {
System.out.println("Stack Underflow");
return true;
}
return false;
}
private boolean isfull() {
if(top == size-1) {
System.out.println("Stack Overflow");
return true;
}
return false;
}
public void push(int n) {
if(isempty()) {
top+=1;
a[top] = n;
}
}
public void pop() {
if(isfull()) {
System.out.println("popped : "+ a[top]);
top-=1;
}
}
public void display() {
for(i=0;i<top;i++) {
System.out.println(a[i]);
}
}
}
here is the main method class
public class Stackex {
public static void main(String[] args) {
Stack s = new Stack();
s.push(2);
s.push(4);
s.display();
}
}
when I try to execute what is get is "Stack underflow" from the isempty() and nothing is displayed after that. Please help me where I need to correct this code.

fix methods push & display:
public void push(int n) {
if (!isfull()) {
top += 1;
a[top] = n;
}
}
public void display() {
for (int i = 0; i <= top; i++) {
System.out.println(a[i]);
}
}

Your call to push only pushes if isempty returns true.
So the first push succeeds and sets top to 0.
The second push never happens because isempty returns false.
So when you go to display your for loop never iterates, because top is 0.

There are some compilation errors to fix first.
In the method display the i is not declared, fix it like this:
public void display() {
for (int i = 0; i < top; i++) { // add int i = 0
System.out.println(a[i]);
}
}
Than change this:
private int[] a;;
private int ijk]kkkk
To this:
private int[] a;
Now your issue is because isempty returns false. So change the push method like this:
public void push(int n) {
if (!isfull()) {
top += 1;
a[top] = n;
}
}
When you add an element you want to check that the stack is not full.

Related

How can I avoid java.lang.ArrayIndexOutOfBoundsException when joining a Queue?

I'm working on a simple(?) exercise for my Data Structures class. It works fine right up until I have an element leave the queue then try to add another one on at which point I get the following error:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 10 out of bounds for length 10
at queueExercise.IntegerQueue.join(IntegerQueue.java:20)
at queueExercise.IntegerQueueTest.main(IntegerQueueTest.java:27)
My code is as follows:
Queue Constructor Class:
public class IntegerQueue {
private int[] queue;
private int front;
private int end;
private int noInQueue;
private int count;
private boolean full;
public IntegerQueue(int max) {
queue = new int[max];
front = end = 0;
full = false;
}
public void join(int newValue) {
if (isFull()==false) {
queue[end] = newValue;
count++;
if (end == queue.length) {
end = 0;
}
else {
end++;
}
}else
System.out.println("Error: Queue Full");
}
public int leave() {
if (isEmpty()==false) {
noInQueue = queue[front];
queue[front]=0;
front++;
if (front==queue.length) {
front = 0;
}
count--;
}
else {
System.out.println("Error: Queue Empty");
}
System.out.println("Leaving: "+noInQueue);
return noInQueue;
}
public boolean isEmpty() {
if (count == 0){
return true;
}
else
return false;
}
public boolean isFull() {
if (count >= queue.length) {
return true;
}
else
return false;
}
public void printQueue() {
if (!isEmpty()) {
System.out.println("Printing Queue");
int pos = front;
int i =0;
while(i<queue.length) {
System.out.println(queue[pos]);
pos++;
i++;
if (pos >=queue.length) {
pos = 0;
}
}
}
}
}
Test Class
public class IntegerQueueTest {
static IntegerQueue q = new IntegerQueue(10);
public static void main(String[] args) {
int j;
System.out.println("Creating Queue");
for (int i = 0; i <10; i++) {
j = (int)(Math.random()*100);
if (!q.isFull()) {
q.join(j);
System.out.println("Adding: "+j);
}
}
q.printQueue();
q.join(112);
q.leave();
q.leave();
q.leave();
q.printQueue();
q.join(112);
q.join(254);
q.printQueue();
}
}
The problem is in the join method and more precisely in the condition if (end == queue.length). All you have to do is change it to if (end == queue.length - 1).

Can I add elements to a java queue using array without defining the front and the rear? I am having trouble with this

I am having trouble using enqueue and dequeue functions. I want to add elements without defining the front and rear in my scope.
public class MyStaticQueue
{
private int items[] ;
private int noOfItems = 0;
private int maxItems;
public MyStaticQueue(int m)
{
this.maxItems = m;
this.items = new int[maxItems];
this.noOfItems = 0;
}
public boolean isEmpty()
{
if(noOfItems == 0)
{
return true;
}
else
{
return false;
}
}
public int first()
{
return items[0];
}
public void add(int item)
{
for (int i=0; i<items[maxItems]; i++)
{
if (items[i] == 0)
{
items[i] = item;
}
noOfItems++;
}
}
}

Hello! I'm having trouble printing (Java)

The program is meant to modify the List items (defined at top), and there appears to be trouble printing the modified version to console.
Could I get some tips as to where (and perhaps what, for efficiency) to modify?
import java.util.*;
public class Quiz4 {
public static class ItemHolder{
private List<Integer> items = new ArrayList<>();
public List<Integer> getItems(){
return items;
}
public void addItems(Integer item){
items.add(item);
}
public int size(){
return items.size();
}
public String toString(){
return items.toString();
}
public void remove(Object obj) {
items.remove(obj);
}
public boolean equals(int a, int b){
boolean ret = false;
if (a == b){
ret = true;
}
return ret;
}
public int get(int index){
return items.get(index);
}
}
public static ItemHolder modify(ItemHolder items){
for (int i = 0; i < items.size(); ){
if(items.get(i) == (items.get(i+1))){
items.remove(items.get(i));
}
}
return items;
}
public static void main(String[] args){
ItemHolder items = new ItemHolder();
Scanner up = new Scanner(System.in);
items.getItems();
for (int i = 0; i < 6; i++){
System.out.println("Please enter number. -1 to quit");
String input = up.nextLine();
int check = Integer.parseInt(input);
if (check >= 0){
items.addItems(check);
}
else{
continue;
}
}
modify(items);
System.out.println(items);
up.close();
}
}
Thank you!
Modify your Modify method it will work
for (int i = 0; i < items.size()-1;i++ ){
if(items.get(i) == (items.get(i+1))){
items.remove(items.get(i));
}

How do I test delete() in the class growingArray

I'm learning the Growing Array in Java, and I implemented the method delete() in the following Code.
Now I want to test this method for a example array [1,2,3,4,5,6,7]
What do I have to write in the Main method?
import java.util.Arrays;
public abstract class GrowingArray {
protected Object[] array;
protected static final int primaryQty = 10;
protected static final int secondaryQty = 5;
protected int index = 0;
public GrowingArray() {
array = new Object[primaryQty];
}
public GrowingArray(int size) {
array = new Object[size];
}
protected void grow() {
int oldsize = array.length;
int newsize = oldsize + secondaryQty;
Object[] loc = new Object[newsize];
for (int i = 0; i < oldsize; i++)
loc[i] = array[i];
array = loc;
}
public Object get(int at) {
return array[at];
}
public int getLength() {
return array.length;
}
public void add(Object obj) {
if (index < array.length)
array[index++] = obj;
else {
grow();
array[index++] = obj;
}
}
public void delete(int x) {
for (int i = x; i < array.length; i++) {
if (i == array.length - 1) {
array[i] = null;
System.out.println(array.toString());
} else {
array[i] = array[i + 1];
System.out.println(array.toString());
}
}
}
#Override
public boolean equals(Object obj) {
if (obj instanceof GrowingArray) {
return Arrays.equals(array, ((GrowingArray) obj).array);
}
return false;
}
#Override
public String toString() {
return Arrays.toString(array);
}
public static void main(String args[]) {
//test ?????
}
}
Your class is abstract. Remove abstract from the class definition.

Problem Adding incremented class member variable to arraylist inside loop

Trying to add an incremented class member variable 'nNodeIndex' to arraylist, but at the end of the loop all the values stored are identical to the last iteration increment??
Class with member variable:
import java.util.ArrayList;
public class Graph {
private static ArrayList<GraphNode> Nodes = new ArrayList<GraphNode>();
private static ArrayList<GraphEdge> Edges = new ArrayList<GraphEdge>();
private static boolean diGraph;
private static int nNodeIndex;
private boolean uniqueEdge(int from, int to)
{
for(int i=0; i< Edges.size(); i++){
if(Edges.get(i).from() == from && Edges.get(i).to() == to)
return false;
}
return true;
}
private void removeInvalidEdges(int nodeIndex)
{
for(int i=0; i<Edges.size(); i++)
{
if(Edges.get(i).from() == nodeIndex)
Edges.remove(i);
if(Edges.get(i).to() == nodeIndex)
Edges.remove(i);
}
}
Graph(boolean directionalGraph)
{
diGraph = directionalGraph;
nNodeIndex = 1;
}
public GraphNode getNode(int nodeIndex)
{
return Nodes.get(nodeIndex);
}
public int getIndexByVector(int x, int y)
{
for(int i=0; i<Nodes.size(); i++)
{
if(Nodes.get(i).x() == x && Nodes.get(i).y() == y)
return i;
}
return -1;
}
public int nextFreeNodeIndex(){ return nNodeIndex; }
public void addNode(GraphNode node)
{
if(Nodes.size() > 0)
Nodes.add(node.index()-1, node);
else
Nodes.add(node);
nNodeIndex++;
}
public void removeNode(int index)
{
Nodes.get(index).setIndex(-1);
removeInvalidEdges(index);
}
public void addEdge(GraphEdge edge)
{
if(uniqueEdge(edge.from(), edge.to()))
Edges.add(edge);
if(!diGraph)
{
if(uniqueEdge(edge.to(), edge.from()))
Edges.add(new GraphEdge(edge.to(), edge.from()));
}
}
public void removeEdge(GraphEdge edge)
{
for(int i=0; i<Edges.size(); i++)
if(Edges.get(i).from() == edge.from() &&
Edges.get(i).to() == edge.to())
{
Edges.remove(i);
}
}
public int totalNodes(){ return Nodes.size(); }
public int totalEdges(){ return Edges.size(); }
public int nActiveNodes()
{
int count = 0;
for(int i=0; i<Nodes.size(); i++)
{
if(Nodes.get(i).index() != -1 )
count++;
}
return count;
}
public void reset()
{
nNodeIndex = 1;
Nodes.clear();
Edges.clear();
}
}
Use within main class:
for(int row = 1; row <= boardWidth; row++){
for(int col = 1; col <= boardHeight; col++){
graph.addNode(new GraphNode(graph.nextFreeNodeIndex(), row, col));
}
}
Graph Node class:
public class GraphNode extends Square {
private static int indexNum;
GraphNode(int n, int x, int y)
{
super(x,y);
indexNum = n;
}
public int index(){ return indexNum; }
public void setIndex(int index){ indexNum = index; }
}
Do you need to show us the GraphNode class? I wonder if the node index held by it (set by the first parameter passed in its constructor) is a static variable.

Categories