This my code for a circularly linked array based queue.
public class ArrayQueue{
private Object[] theArray;
private int currentSize;
private int front;
private int rear;
static final int DEFAULT_CAPACITY=10;
public ArrayQueue(){
theArray=new Object[DEFAULT_CAPACITY];
makeEmpty();
}
public void makeEmpty(){
currentSize=0;
rear=-1;
front=0;
}
public void enqueue(Object x) throws OverFlow{
if (isFull())
throw new OverFlow("Array size exceeded");
else{
rear=increment(rear);
theArray[rear]=x;
currentSize++;
}
}
public Object dequeue()throws UnderFlow{
if (isEmpty())
throw new UnderFlow("Empty array");
else{
Object returnValue=theArray[front];
theArray[front]=null;//check if this has to be done
front=increment(front);
currentSize--;
return returnValue;
}
}
public object getFront() throws UnderFlow{
if (isEmpty())
throw new UnderFlow("Empty array");
else
return theArray[front];
}
public boolean isEmpty(){
if (currentSize==0)
return true;
else
return false;
}
public boolean isFull(){
if (currentSize==theArray.length)
return true;
else
return false;
}
public int increment(int x){
if (x+1==currentSize)
x=0;
else
x++;
return x;
}
}
When I compiled this I get errors as cannot find symbol throw new OverFlow.
How to get rid of this issue.
Related
public class StackSimple{
private long capacity=1000;//maximum size of array
private int idx_top;
private Object data[];
public StackSimple(int capacity)
{
idx_top=-1;
this.capacity=capacity;
data = new Object[capacity];
}
public boolean isEmpty(){
return(idx_top<0);
}
public boolean isFull(){
return(idx_top>=capacity-1);
}
public int size()
{
return idx_top+1;
}
public boolean push(Object x){
if (isFull()){
throw new IllegalArgumentException("ERROR:Stack Overflow.Full Stack");
}
else
{`enter code here`data[++idx_top]=x;
return true;
}
}
public Object pop(){
if(isEmpty())
throw new IllegalArgumentException("ERROR:Stack Underflow.Empty Stack.");
else{
return data[idx_top--];
}
}
public Object top(){
if (isEmpty())
throw new IllegalArgumentException("ERROR:Stack Underflow.Empty Stack.");
else{
return data[idx_top];
}
}
public void print()
{`
for (int i=size()-1;i>=0;i--)
System.out.println(data[i]);
}
}
public class Stack_Exercise {
public static void main(String[] args) {
StackSimple s = new StackSimple(capacity:3);//error shows here
s.push(x:"books");`enter code here`
s.push(x:"something");
s.push(x:"200");
s.print();
System.out.println("Size=" +s.size());
}
}
Why doesn't this work?
Why does it say invalid statement while creating the StackSimple object? The problem is in the main class while running it. There are errors while pushing the elements.
Error while compiling
When passing parameters to a function you just pass the values.
In your case not StackSimple(capacity:3) but just StackSimple(3)
First question, which version of Java are you using.
Second, in Java you should be passing as a variable instead of StackSimple(capacity:3). Change your main method to below, here is my recommendation:
StackSimple s = new StackSimple(3);
s.push("books");
s.push("something");
s.push("200");
s.print();
System.out.println("Size=" +s.size());
You are not at all pushing the value in the stack, your pusch function is not working as it is expected to work.
Here is the correct program.
class StackSimple {
private long capacity = 1000;// maximum size of array
private int idx_top;
private Object data[];
public StackSimple(int capacity) {
idx_top = -1;
this.capacity = capacity;
data = new Object[capacity];
}
public boolean isEmpty() {
return (idx_top < 0);
}
public boolean isFull() {
return (idx_top >= capacity - 1);
}
public int size() {
return idx_top + 1;
}
public boolean push(Object x) {
if (isFull()) {
throw new IllegalArgumentException("ERROR:Stack Overflow.Full Stack");
} else {
data[++idx_top] = x;
return true;
}
}
public Object pop() {
if (isEmpty())
throw new IllegalArgumentException("ERROR:Stack Underflow.Empty Stack.");
else {
return data[idx_top--];
}
}
public Object top() {
if (isEmpty())
throw new IllegalArgumentException("ERROR:Stack Underflow.Empty Stack.");
else {
return data[idx_top];
}
}
public void print() {
for (int i = size() - 1; i >= 0; i--)
System.out.println(data[i]);
}
}
public class test {
public static void main(String[] args) {
StackSimple s = new StackSimple(3);// error shows here
s.push("books");
s.push("something");
s.push("200");
s.print();
System.out.println("Size=" + s.size());
}
}
public class ArrayQueue{
private Object[] theArray;
private int currentSize;
private int front;
private int rear;
static final int DEFAULT_CAPACITY=10;
public ArrayQueue(){
theArray=new Object[DEFAULT_CAPACITY];
makeEmpty();
}
public void makeEmpty(){
currentSize=0;
rear=-1;
front=0;
}
public void enqueue(Object x) throws OverFlow{
if (isFull())
throw new OverFlow("Array size exceeded");
else{
rear=increment(rear);
theArray[rear]=x;
currentSize++;
}
}
public Object dequeue()throws UnderFlow{
if (isEmpty())
throw new UnderFlow("Empty array");
else{
Object returnValue=theArray[front];
theArray[front]=null;//check if this has to be done
front=increment(front);
currentSize--;
return returnValue;
}
}
public Object getFront() throws UnderFlow{
if (isEmpty())
throw new UnderFlow("Empty array");
else
return theArray[front];
}
public boolean isEmpty(){
if (currentSize==0)
return true;
else
return false;
}
public boolean isFull(){
if (currentSize==theArray.length)
return true;
else
return false;
}
public int increment(int x){
if (x+1==currentSize)
x=0;
else
x++;
return x;
}
public static void main (String args[]){
ArrayQueue q=new ArrayQueue();
q.enqueue("1");
}
}
public class OverFlow extends Exception{
public OverFlow(){
super();
}
public OverFlow(String s){
super(s);
}
}
public class UnderFlow extends Exception{
public UnderFlow(){
super();
}
public UnderFlow(String s){
super(s);
}
}
When I try to run this I get an error as unreported exception OverFlow,Must be caught or declared to be thrown.
I am new to Java and programming but I have to learn a data structures course.Therefore if someone can tell me whats wrong here and how to correct it it would be really helpful
Any class that extends Exception (with the exception of RuntimeException) is considered a checked exception. This means that you, the programmer, must either catch it in a try...catch block, or throw the exception elsewhere.
The problem is that your method enqueue() throws a checked exception.
You could solve this one of two ways:
Wrap the call to enqueue in a try...catch block, or
Add throws OverFlow to main.
Examples of both:
try {
q.enqueue("1");
} catch (OverFlow e) {
e.printStackTrace();
}
public static void main(String[] args) throws OverFlow {
ArrayQueue q=new ArrayQueue();
q.enqueue("1");
}
I am trying to implement the stack i.e., DSAStack.java using my linked list i.e., DSALinkedList.java
How do I do it? I think I am supposed to have push() perform an insertFirst() and pop() do a peekFirst() and removeFirst() to get the LIFO behaviour? and what about isEmpty()
and the other methods?
I am not sure, please help me out. A clear explanation with a code would be much appreciable. Thank you in advance!
Here is the DSAStack.java
public class DSAStack implements Iterable {
public static int DEFAULT_CAPACITY = 100;
private DSALinkedList list;
private int count;
private Object[] stack;
public DSAStack() {
count = 0;
stack = new Object[DEFAULT_CAPACITY];
}
public DSAStack(int maxCapacity) {
count = 0;
stack = new Object[maxCapacity];
}
public int getCount() {
return count;
}
public boolean isEmpty() {
boolean empty = (count == 0);
return empty;
}
public boolean isFull() {
boolean full = (count == stack.length);
return full;
}
public void push(Object value) {
if (isFull())
throw new IllegalArgumentException("Stack is full");
else
stack[count] = value;
count++;
}
public Object pop() {
Object topVal = top();
count--;
return topVal;
}
public Object top() {
Object topVal;
if (isEmpty())
throw new IllegalArgumentException("Stack is empty");
else
topVal = stack[count-1];
return topVal;
}
public Iterator iterator() {
return list.iterator();
}
}
AND here is the DSALinkedList.java
import java.util.*;
public class DSALinkedList {
public DSAListNode head;
public DSAListNode tail;
Object[] newValue;
public DSALinkedList() {
head = null;
tail = null;
}
public void insertFirst(Object newValue){
DSAListNode newNd;
newNd = new DSAListNode(newValue);
if (head == null) {
head = newNd;
tail = newNd;
} else {
newNd.setNext(head);
head = newNd;
}
}
public void insertLast(Object newValue){
DSAListNode newNd;
newNd = new DSAListNode(newValue);
if(head == null){
head = newNd;
} else {
tail.next = newNd;
tail = newNd;
}
}
public boolean isEmpty() {
return (head == null);
}
public Object peekFirst(){
Object nodeValue;
if (head == null)
throw new IllegalArgumentException("head is empty");
else
nodeValue = head.getValue();
return nodeValue;
}
public Object peekLast(){
Object nodeValue;
if (head == null)
throw new IllegalArgumentException("head is empty");
else
nodeValue = tail.getValue();
return nodeValue;
}
public Object removeFirst(){
Object nodeValue;
if (head == null){
throw new IllegalArgumentException("head is empty");
} else {
nodeValue = head.getValue();
head = head.getNext();
}
return nodeValue;
}
}
Your DSAStack class is meant to be the interface between the user and linkedlist. So therefore the class provides the LIFO interface and forces it on the user. From here, it should hide the implementation from the linkedlist so the user doesn't have to worry about insertingLast or insertingFirst, they just want to insert.
So to answer your question. The DSAStack needs to perform the following actions:
- size() -> returns int size
- push(Object e) -> returns bool (able to be inserted)
- pop() -> returns Object and removes it from linkedlist
- peek() -> returns Object
- isEmpty() -> returns bool if empty
Your DSAStack isn't meant to hold any data. So you don't need the count or stack variable. Instead, we need to store these inside the DSALinkedList class. DSAStack should therefore instantiate a DSALinkedList object, pass the maxCapacity, and initiate the object.
When the user says that they want to use pop() on DSAStack, the class then needs to tell DSALinkedList, hey! I want to pop one of your objects! Now DSALinkedList needs to implement the details here.
Rewriting your code would be like this:
public DSAStack(int maxCapacity) {
list = new DSALinkedList[maxCapacity];
}
public int getCount() {
return list.size();
}
public boolean isEmpty() {
return list.isEmpty();
}
public boolean isFull() {
return list.isFull();
}
public void push(Object value) {
list.insertLast(value);
}
public Object pop() {
return list.removeLast();
}
public Object top() {
return list.peekLast();
}
public Iterator iterator() {
return list.iterator();
}
}
I was studying about hashset in java and for that I am writing creating my own hashset which will double its size everytimme the threshold value is reached..here I am keeping the threshold as 0.75 of original size . However my code is running into an infinite loop. I tried debugging it but was not able to find my error...
here is the code
package drafta;
import java.util.Iterator;
import java.util.NoSuchElementException;
public class HashSet
{
private Node[] buckets;
private int currentSize;
private int current;
public HashSet(int bucketsLength)
{
buckets=new Node[bucketsLength];
currentSize=0;
}
public boolean contains(Object x)
{
return false;
// don't implement for the draft
}
public boolean add(Object x)
{
int key=gethashcode(x);
Node node = buckets[key];
while(node!=null){
if(node.data.equals(x)){
return false;
}
}
if(buckets[current]==null){
node = new Node(x);
current=key;
buckets[key]=node;
currentSize++;
}else{
node = new Node(x);
node.next=buckets[current];
current=key;
buckets[key]=node;
currentSize++;
}
System.out.println("add successful "+ x);
System.out.println(" size "+currentSize+" rehash "+buckets.length*0.75);
if(currentSize>(buckets.length*0.75)){
rehash();
}
return true;
}
private void rehash() {
Node temp=buckets[current];
Object s[]=new Object[buckets.length];
buckets=new Node[2*buckets.length];
currentSize=0;
int i=0;
while(temp!=null){
s[i]=temp.data;
temp=temp.next;
i++;
}
while(i>0){
add(s[--i]);
}
}
public boolean remove(Object x)
{
return false;
// don't implement for draft
}
public int gethashcode(Object x){
int hc = x.hashCode();
if(hc<0)
hc=-hc;
return (hc%buckets.length);
}
public Iterator<Object> iterator()
{
Iterator <Object> i=new HashSetIterator();
return i;
//
}
public int size()
{
return currentSize;
//
}
private void resize(int newLength)
{
}
public int getlength()
{
return buckets.length;
//
}
class Node
{
public Object data;
public Node next;
public Node(Object x) {
data=x;
}
public String toString(){
return data.toString();
}
}
class HashSetIterator implements Iterator<Object>
{
private int bucket=0;
private Node currentnode;
public HashSetIterator()
{
currentnode=buckets[current];
}
public boolean hasNext()
{
if(currentnode.next!=null)
return true;
else
return false;
//
}
public Object next()
{
return currentnode.next;
//
}
#Override
public void remove() {
currentnode.next=currentnode.next.next;
}
}
}
this is the main class which I am using to test my code
package drafta;
import java.util.Iterator;
public class HashSetTester
{
public static void main(String[] args)
{
HashSet names = new HashSet(5);
names.add("Harry");
names.add("Sue");
names.add("Nina");
System.out.println(names.size() + " " + names.getlength());
names.add("Susannah");
System.out.println(names.size() + " " + names.getlength());
System.out.println();
names.add("Larry");
names.add("Juliet");
names.add("Katherine");
names.add("Romeo");
names.add("Maria");
System.out.println(names.size() + " " + names.getlength());
names.add("Ann");
names.add("Taylor");
System.out.println(names.size() + " " + names.getlength());
}
}
can someone please point out my mistake..the code is going into infintie loop when it calls rehash for second time..first time it goes through correctly...
You arn't changing any conditions in your while loop in the add method - so there is no reason for it to break out.
while(node!=null){
if(node.data.equals(x)){
return false;
}
}
You will continue looping until the node is null (which never gets set) or the node data ever equals x, but the data value also never gets set.
Can someone explain what am I doing wrong here ?
I am trying to create a queue from two stacks as per a book exercise. I get error "Stack Underflow" from the peek function. But everything seems right to me :P Please explain. Thanks!
//Program to implement Queue using two Stacks.
import java.util.NoSuchElementException;
public class Ex3_5_Stack {
int N;
int countOfNodes=0;
private Node first;
class Node {
private int item;
private Node next;
}
public Ex3_5_Stack() {
first=null;
N=0;
}
public int size() {
return N;
}
public boolean isEmpty() {
return first==null;
}
public void push(int item){
if (this.countOfNodes>=3) {
Ex3_5_Stack stack = new Ex3_5_Stack();
stack.first.item=item;
N++;
} else {
Node oldfirst = first;
first = new Node();
first.item=item;
first.next=oldfirst;
N++;
}
}
public int pop() {
if (this.isEmpty())
throw new NoSuchElementException("Stack Underflow");
int item = first.item;
first=first.next;
return item;
}
public int peek() {
if (this.isEmpty())
throw new NoSuchElementException("Stack Underflow");
return first.item;
}
}
And MyQueue file
public class Ex3_5_MyQueue {
Ex3_5_Stack StackNewest,StackOldest;
public Ex3_5_MyQueue() {
super();
StackNewest = new Ex3_5_Stack();
StackOldest = new Ex3_5_Stack();
}
public int size() {
return StackNewest.size()+StackOldest.size();
}
public void add(int value) {
StackNewest.push(value);
}
private void transferStack() {
if (StackOldest.isEmpty()) {
while (StackNewest.isEmpty()) {
StackOldest.push(StackNewest.pop());
}
}
}
public int peek() {
this.transferStack();
return StackOldest.peek();
}
public int remove() {
this.transferStack();
return StackOldest.pop();
}
public static void main(String[] args) {
Ex3_5_MyQueue myQueue = new Ex3_5_MyQueue();
myQueue.add(4);
myQueue.add(3);
myQueue.add(5);
myQueue.add(1);
System.out.println(myQueue.peek());
}
}
In transferStack(), you're missing an exclamation mark. It should be:
private void transferStack(){
if(StackOldest.isEmpty()){
while(!StackNewest.isEmpty()){ // you forgot it here
StackOldest.push(StackNewest.pop());
}
}
}