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();
}
...
}
Related
Why do I keep getting an error when I try to execute this method,
import java.util.List;
import java.util.Optional;
import java.util.function.Predicate;
import java.util.ArrayList;
import java.util.HashSet;
public class BIAOperations <T extends Comparable<T>, E> implements Set<T>
{
private HashSet<T> Set;
public BIAOperations(){
Set = new HashSet<T>();
}
#Override
public boolean isEmpty()
{
if(Set.isEmpty())
{
return true;
}
else
return false;
}
#Override
public int size(){
return Set.size();
}
#Override
public int compareTo(Set<T> o) {
return 0;
}
#Override
public List<T> toList() {
List<T> list = new ArrayList<T>();
list.addAll(Set);
return list;
}
#Override
public Set<T> add(T x) {
Set.add(x);
return this;
}
#Override
public Set<T> remove(T x) {
Set.remove(x);
return this;
}
#Override
public boolean contains(T x)
{
if(Set.contains(x))
return true;
}
else
{
return false;
}
The error which I get is at the contains method at the bottom of the code.
the error I keep getting is void methods cannot return a value and on else I keep getting syntax error on else delete this token.
The else block is outside the method. Fix it as follows:
#Override
public boolean contains(T x)
{
if(Set.contains(x))
return true;
else
return false;
}
EDIT: you can also shorten this code as per #Unholysheep's suggestion in the comment.
#Override
public boolean contains(T x)
{
return Set.contains(x);
}
Also, as per #domdom's suggestion in the comment, use a better name for your object. In Java, I would recommend you use names starting with a small letter for your objects. Typically, names starting with a upper case letter are used for Class names. So instead of Set, use set or customSet or something for your object.
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!
I have created two iterators for an array: the first runs the array by rows (iteratorRow) and then by columns and the second, first by columns and then by rows (iteratorColumn).
I have another class, Matrix, in which I must create two methods for performing iteration (iteratorRowColumn and iteratorColumnRow) that return iterators that have created to be accessible to other classes.
The array must implement the Iterable interface and may be configured (using a Boolean) which of the two iterators it shall be refunded by calling iterator () method.
How can I do that? Do I have to do some getters methods? Something like this?
public Iterator iteratorRowColumn () {
return new iteratorRow;
}
I think that the last sentence of assignment explains a problem very well. I am not sure what part of it is unclear so let me explain in detail:
The array must implement the Iterable interface
public class Matrix<T> implements Iterable<T>
may be configured (using a Boolean)
public Matrix(boolean defaultRowColumnIterator) {
this.defaultRowColumnIterator = defaultRowColumnIterator;
}
which of the two iterators it shall be returning by calling iterator() method
#Override
public Iterator<T> iterator() {
return defaultRowColumnIterator ? iteratorRowColumn() : iteratorColumnRow();
}
Here is a compilable example:
public class Matrix<T> implements Iterable<T> {
T[][] array;
boolean defaultRowColumnIterator;
public Matrix(boolean defaultRowColumnIterator) {
this.defaultRowColumnIterator = defaultRowColumnIterator;
}
// other methods and constructors
public Iterator<T> iteratorRowColumn() {
return null; // your current implementation
}
public Iterator<T> iteratorColumnRow() {
return null; // your current implementation
}
#Override
public Iterator<T> iterator() {
return defaultRowColumnIterator ? iteratorRowColumn() : iteratorColumnRow();
}
}
Something like this:
public class Proba {
Integer[][] array = new Integer[10][10];
public class MyIter implements Iterator<Integer> {
private Integer[] integers;
private int index = 0;;
public MyIter(Integer[] integers) {
this.integers = integers;
}
#Override
public boolean hasNext() {
return index < integers.length -1 ;
}
#Override
public Integer next() {
return integers[index];
}
#Override
public void remove() {
//TODO: remove
}
}
public static void main(String[] args) {
Iterator<Integer> iter = new Proba().getIterator(1);
while (iter.hasNext()) {
System.out.println(iter.next());
}
}
public Iterator<Integer> getIterator(int row) {
return new MyIter(array[row]);
}
}
Is this code a stack?
How I can make it better?
This is my first one.
Can i do this using ArrayList?
public class Stack implements IADT {
private final int[] stackArray = new int[10];
private int top;
private int nr;
public Stack(){
top = -1;
}
#Override
public String pop() {
return Integer.toString(stackArray[top--]);
}
#Override
public String peek() {
return Integer.toString(stackArray[top]);
}
#Override
public void push(String value) {
//...
}
I didn't added the isEmpty() method.
Yes, it is.
But you can add checking for overflow, underflow.
And this will be better if you'll try using collections.
This is an example run in our Java class today with no problem but when I added the files into a new project I am having the following error. Can you please tell me if I have added files wrongly or maybe the professor was using an slightly different version of the files? Can you let me know what's the reason for this error and how to fix it?
The code for each of the file is as following: ArrayGSackIterable.java:
import java.util.Iterator;
public class ArrayGSackIterable<T> extends ArrayGSack<T> implements GSackIterableADT<T> {
public Iterator<T> iterator() {
return new ArrayGSackIterator<T>(items, numItems);
}
}
and for ArrayGSackIterator.java:
import java.util.Iterator;
import java.util.NoSuchElementException;
public class ArrayGSackIterator<E> implements Iterator<E> {
private E[] items;
private int numItems, curr;
public ArrayGSackIterator(E[] gsackitems, int num) {
items = gsackitems;
numItems = num;
}
public boolean hasNext() {
return curr < numItems;
}
public E next() {
if (!hasNext()) throw new NoSuchElementException();
return items[curr++];
}
public void remove() {
}
}
and finally for GSackIterableADT.java:
import java.util.Iterator;
import java.util.NoSuchElementException;
public interface GSackIterableADT<T> extends Iterable<T> {
void add(T item);
T remove() throws NoSuchElementException;
boolean isEmpty();
Iterator<T> iterator();
}
UPDATE: Apparently I had to add these two files from another .zip file. GSackADT.java:
import java.util.NoSuchElementException;
public interface GSackADT<T> {
void add(T item);
T remove() throws NoSuchElementException;
boolean isEmpty();
}
ArrayGSack.java:
import java.util.NoSuchElementException;
public class ArrayGSack<T> implements GSackADT<T> {
// Internal storage and accounting members
protected T[] items;
protected int numItems;
private static final int INIT_SIZE = 100;
public ArrayGSack() {
items = (T[]) new Object[INIT_SIZE];
numItems = 0;
}
public void add(T item) {
if (numItems == items.length) expandStorage();
items[numItems++] = item;
}
public T remove() throws NoSuchElementException {
if (numItems < 1) throw new NoSuchElementException();
return items[numItems--];
}
public boolean isEmpty() {
return numItems == 0;
}
// Internal method to handle capacity issues
private void expandStorage() {
T[] oldItems = items;
items = (T[]) new Object[2 * items.length];
for (int i = 0; i < oldItems.length; i++)
items[i] = oldItems[i];
}
}
Your code is complaining for an unimplemented method remove from interface GSackIterableADT.
Your professor might have done either of these to make it run:
Deleted remove method from GSackIterableADT interface
Marked ArrayGSackIterable as an abstract class