LinkedListStack System.out.println - java

Im working on a LinkedListStack and have to print out for example "size".
here is my LinkedListStack:
public class LinkedListStack {
private class Element {
public Object value;
public Element next;
}
private Element top;
private int size=0;
public void push(Object o) {
Element e=new Element();
e.value=o;
e.next=top;
top=e;
size++;
}
public Object pop() {
if (top!=null) {
Object v=top.value;
top=top.next;
size--;
return v;
} else {
return null;
}
}
public boolean isEmpty(){
return top==null;
}
public int size() {
return size;
}
public Object get(int n) {
Element current=top;
int i=0;
while (i<n && current!=null) {
current=current.next;
i++;
}
if (current==null)
return null;
else
return current.value;
}
}
I know I have to use
System.out.println ("...");
and that i need a new class, let's call it Stacki. Is must contain a main method where i can use the methods and print them out. So that would be:
public class Stacki {
public static void main(String[] args) {
}
}
how do I put
public void size() {
System.out.println ("size is"+size());
}
in that class? Because i cannot use the block as such, an error occurs.
Thank you :)

You instantiate your other class within Stacki, like:
public class Stacki {
public static void main(String[]) {
LinkedListStack stack = new LinkedListStack();
System.out.println("size is: " + stack.size());
... then you probably add some elements, remove some, and whenever you want to:
System.out.println("size is: " + stack.size());
And hint: Stacki is a rather nothing-saying name. Better call that class LinkedListStackTester or something alike. Names always say what the thing they denote is about!
And finally: this is really basic stuff. It doesn't make much sense to create your own stack class, when you have no idea how to put that to use. In that sense: you probably want to spend some hours here and work yourself through those tutorials!

Related

how to realize a queue in java?

I want to do the same thing I did in this code for stack
how can i change it so it will be for queue? I don't want to use stack or LinkedList for that
public StackAsArray(){
this(new DynamicArray());
}
public boolean isEmpty() {
}
public void push(Object o) {
}
public Object pop() {
}
}
You just need to replace your push and pop methods with enqueue and dequeue methods.
enqueue adds elements to the end of the array, while dequeue will remove it from the beginning.
public class QueueAsArray implements Queue {
...
public void enqueue(Object o) {
arr.set(numOfElements, o);
numOfElements++;
}
public Object dequeue() {
if(isEmpty()) { // an empty check is a MUST
return null;
}
numOfElements = numOfElements - 1;
Object res = arr.get(0);
arr.set(0, null); // not 100% sure this works, but since this is a homework question, its upto you to figure out. The logic is to remove the 0th element.
return res;
}
}

How to implement the remove method in the Iterator class for a stack?

I'm writing an ArrayStack class that uses an iterator. I know using an iterator for a stack doesn't necessarily make sense but this is for homework purposes. I am having trouble with the remove method. I understand its description but I'm having trouble implementing it. Here is the inner class of my program:
private class StackIterator implements Iterator<Item> {
private int index;
private boolean canremove;
public StackIterator() {
index = size - 1;
canremove = false;
}
#Override
public boolean hasNext()
{
return index > 0;
}
#Override
public Item next()
{
if (!hasNext()) {
throw new NoSuchElementException("There is no next element"+
" in the stack.");
}
canremove = true;
return contents[--index];
}
#Override
public void remove() {
if (!canremove) {
throw new IllegalStateException("Can only remove an element"
+ "after a call to the next method has been made.");
}
canremove = false;
}
}
How do I actually go about removing the element? Do I just decrease size? Or do I need more variables to keep track? Any help is appreciated.

Trouble casting an interface to an implemented class

Here is my class:
public class LinkedListSet implements Set {
private class Node //much easier as a private class; don't have to extend
{
private int data;
private Node next;
public Node (){}
public Node (int x)
{
data = x;
}
public int data()
{
return data;
}
public Node next()
{
return next;
}
}
private Node first;
private int Size;
private int whichList; //used to identify the particular LL object
Here is my interface:
public interface Set {
public boolean isEmpty();
public void makeEmpty();
public boolean isMember(int x);
public void add(int x);
public void remove(int y);
public void union(Set other, Set result);
public void intersection (Set other, Set result);
public void difference (Set other, Set result);
#Override
public String toString();
#Override
public boolean equals(Object other);
public void setList(int i); //i added this to use it as an identifier for each
//list element in the set array
public String getListId(); //these two extra methods make life easier
}
I have a method like this (in the LinkedListSet class):
public void difference (Set other, Set result)
{
if (other.isEmpty())
{
System.out.println("The set is empty before cast");
}
LinkedListSet othr = (LinkedListSet) other;
LinkedListSet res = (LinkedListSet) result;
if (this.isEmpty() || othr.isEmpty())
{
if (othr.isEmpty())
System.out.println("The set is empty after cast");
if (this.isEmpty())
System.out.println("This is also empty");
return;
}
differenceHelper(this.first, othr.first, res);
result = res;
}// the print statements were added for debugging
The problem is, in the above method I am unable to cast the Set Other into its linked list implementation. When I call this method in the main program, the parameter is actually of type linked list (so I don't get any errors obviously).
However, all the instance variables are null. The list is empty before and after I cast it (when it actually isn't empty). I know this is because the interface doesn't include any information about the Nodes, but is there anything I can do other than editing the interface to incorporate the Node?
I hope I've made this clear enough. Any help would be appreciated.
edit:
In the main program I created an array of Sets.
Set[] sets = new Set[7];
for (int i = 0; i< sets.length; i++) //initialize each element
{
sets[i] = new LinkedListSet();
}
each list has nodes with data values which are added on later on in the code...
then I call the difference method.
sets[0].difference(sets[1], sets[4])
sets[1].isEmpty returns true for some reason (even though it is not).
If I were to do something like:
System.out.println(sets[1].first.data()) I would have no problem whatsoever.
For some reason all the values become null when the parameters are passed to the difference method.
public boolean isEmpty()
{
return first == null;
}
I tested what you are trying to do with the following code and I see no problems:
import org.junit.Test;
public class RandomCastTest {
public interface Set {
boolean isEmpty();
void add(int x);
void difference(Set other, Set result);
#Override
String toString();
#Override
boolean equals(Object other);
}
public class LinkedListSet implements Set {
private class Node //much easier as a private class; don't have to extend
{
private int data;
private Node next;
public Node() {
}
public Node(int x) {
data = x;
}
public int data() {
return data;
}
public Node next() {
return next;
}
public void next(Node node) {
next = node;
}
}
private Node first;
private int Size;
private int whichList; //used to identify the particular LL object
#Override
public boolean isEmpty() {
return first == null;
}
#Override
public void add(int x) {
Node node = new Node(x);
if (first == null) {
first = node;
} else {
Node currentNode;
Node nextNode = first;
do {
currentNode = nextNode;
nextNode = currentNode.next();
} while (nextNode != null);
currentNode.next(node);
}
Size++;
}
#Override
public void difference(Set other, Set result) {
if (other.isEmpty()) {
System.out.println("The set is empty before cast");
}
LinkedListSet othr = (LinkedListSet) other;
LinkedListSet res = (LinkedListSet) result;
if (this.isEmpty() || othr.isEmpty()) {
if (othr.isEmpty())
System.out.println("The set is empty after cast");
if (this.isEmpty())
System.out.println("This is also empty");
return;
}
result = res;
}
}
#Test
public void test() {
Set[] sets = new Set[7];
for (int i = 0; i < sets.length; i++) {
sets[i] = new LinkedListSet();
}
for (int i = 0; i < 5; i++) {
sets[1].add(i);
}
for (int i = 5; i < 10; i++) {
sets[0].add(i);
}
sets[0].difference(sets[1], sets[4]);
// ... find difference
}
}
To simplify I removed unimplemented methods from the interface. Also added the add method implementation. Please see if it works for you.

myArraylist.size() cannot find symbol error Java

I made a stack using java generics in order to make a program that calculates a mathematical expression.
Here is the code of the stack:
import java.util.ArrayList;
public class Stack<T>
{
private ArrayList<T> stack;
public Stack()
{
stack = new ArrayList<T>();
}
public void push(T item)
{
stack.add(item);
System.out.println(item);
}
public T pop()
{
T last;
last = stack.remove((stack.size() - 1));
System.out.println(last);
return(last);
}
public boolean isEmpty()
{
return stack.isEmpty();
}
}
but when i try to do:
Stack<Integer> number = new Stack<Integer>();
in another class which calculates the expression
and then use it to do the following:
if(number.size()>=2)
{
//calculation
}
since i have an ArrayList , i get error:canot find symbol in number.size() , can you help me?
public class Stack<T>
doesn't have a size() method. You need to impelement one like this
public int size() {
return stack.size();
}
You have to implement the size() method in your Stack class.
public class Stack<T> {
...
public int size() {
return this.stack.size();
}
...
}

Making a Stack Method in Java

Is there any simple way to get the stack to display then empty itself inside the method "PrintAndEmpty"? I need the print and empty inside the method PrintAndEmpty and not the main. The codes are:
import java.util.*;
class Stack<E> implements StackInterface<E> {
private ArrayList<E> items;
public Stack() { // default constructor; creates an empty stack
items = new ArrayList<E>(); // initial capacity is 10
}
public Stack(int initialCapacity) {
//one argument constructor, creates a stack with initial capacity initialCapacity
items = new ArrayList<E>(initialCapacity);
}
public void push(E x) {
items.add(x); //uses the ArrayList method add(E o)
}
public E pop() {
if (empty()) // determine whether or not there is an item to remove
return null;
return items.remove(items.size()-1); //uses the ArrayList method remove(int n)
}
public boolean empty() {
return items.isEmpty();//uses the ArrayList method isEmpty()
}
public int size() {
return items.size(); //uses the ArayList method size()
}
public E peek() {
if (empty()) // determine whether or not there is an item on the stack
return null;
return items.get(items.size()-1); //uses the ArrayList method get(int i)
}
public void PrintAndEmpty()
{
// I want to print then empty the stack here, not in the main method.
}
Main method
public static void main (String[] args) // for demonstration only
{
Stack<Student> s = new Stack<Student>();
// push five Student references onto s
s.push(new Student("Spanky", "1245"));
s.push(new Student("Alfalfa", "1656"));
s.push(new Student("Darla", " 6525"));
s.push(new Student("Stimie", "1235"));
s.push(new Student("Jackie", "3498"));
// The data below is what I am trying to put in the PrintAndEmpty method
while(!s.empty())
System.out.println(s.pop().getName());
System.out.println();
System.out.println("The size of the stack is now "+s.size());
}
The Student Class for testing purposes:
public class Student
{
private String name;
private String id;
public Student()
{
name = "";
id = "";
}
public Student (String n, String idNum)
{
name = n;
id = idNum;
}
public String getName()
{
return name;
}
public String getID()
{
return id;
}
public void setName(String n)
{
name = n;
}
public void setID( String idNum)
{
id = idNum;
}
public boolean equals(Object o) // name and id are the same
{
return ( (((Student)o).name).equals(name) &&
(((Student)o).id).equals(id) );
}
}
I am all out of ideas as far as getting this to work. If anyone has suggestions, please let me know. I would greatly appreciate it!
Not sure why you'd want to do that, but here is how you would do it:
// PrintAndEmpty 'this' stack.
public void PrintAndEmpty()
{
// The condition to check - e.g. 'this' stack.
while(!this.empty()) {
// Pop from the stack - e.g. 'this' stack.
System.out.println(this.pop().getName());
}
}

Categories

Resources