Iterating over object of the class - java

In the following code, I instantiated an object of the class and wondering whether I am heading in the right direction or not?. Since it's not a collection, is there a way I can iterate through the items I am inserting using stack class object? Or is there something wrong with the solution design part?
package stack;
import java.util.LinkedList;
import java.util.Queue;
public class StackUsingQPartII {
Queue<Integer> q1 = new LinkedList<Integer>();
Queue<Integer> q2 = new LinkedList<Integer>();
public int pop() {
if (q1.peek() == null) {
System.out.println("The stack is empty, nothing to return");
int i = 0;
return i;
} else {
int pop = q1.remove();
return pop;
}
}
public void push(int data) {
if (q1.peek() == null) {
q1.add(data);
} else {
for (int i = q1.size(); i > 0; i--) {
q2.add(q1.remove());
}
q1.add(data);
for (int j = q2.size(); j > 0; j--) {
q1.add(q2.remove());
}
}
}
public static void main(String[] args) {
StackUsingQPartII st = new StackUsingQPartII ();
st.push(2);
}
}

You can make the class enclosing your stack implementation return an iterator() to iterate over the elements in the queue. The iterator() functionality can simply be delegated to the underlying container class holding the stack elements.
public class StackUsingQPartII implements Iterable<Integer>{
#Override
public Iterator<Integer> iterator() {
return q1.iterator();
}
public static void main(String[] args) {
StackUsingQPartII st = new StackUsingQPartII();
st.push(2);
Iterator<Integer> it = st.iterator();
while (it.hasNext()) {
Integer i = it.next();
System.out.println(i);
}
}
}

Related

why can't I use parent method? (ArrayList)

everybody
I have some questions~
In the main method , int size = s.getSize()
but when I change to int size = s.size()
Why compiler show NoSuchMethodError?
Mystack is a ArrayList's child class
Why can't I use size() method?
package ch11;
import java.util.ArrayList;
import java.util.Scanner;
public class ch11_10 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
MyStack s = getStack(input);
int size = s.getSize();//換成s.size()
for (int i = 0; i < size; i++) {
System.out.println(s.pop());
}
}
public static MyStack getStack(Scanner input) {
System.out.print("Enter five strings: ");
MyStack s = new MyStack();
for (int i = 0; i < 5; i++) {
s.push(input.next());
}
return s;
}
}
class MyStack extends ArrayList {
public int getSize() {
return size();
}
public Object peek() {
return get(size() - 1);
}
public Object pop() {
Object o = get(size() - 1);
remove(size() - 1);
return o;
}
public void push(Object o) {
add(o);
}
#Override
public String toString() {
return "stack: " + toString();
}
}

compare an element of a list with the following in a recursively way

Hi,
Update: Thanks for all your suggestion
assuming that, this exercise it's like a rebus,
I have a list of numbers made with the concept of Cons and Nil,
List l = new Cons(**3**, new Cons(**2**,new Cons(**1**, new
Cons(**4**, new Cons(**1**, new Nil())))));
and I want to count how many of them are immediately followed by a lower number, recursively.
For example
[5,0,5,3].count() == 2, [5,5,0].count() == 1
The count() method is made by me (it cannot have any parameters), the rest is default, and I can't make and other method or use already defined one's like add(),size()...
The "NEXT" must have the next value after the current elem but I can't get a solution.
Any solutions are welcome.
abstract class List {
public abstract boolean empty();
public abstract int first();
public abstract int count();
}
class Cons extends List {
private int elem;
private List next;
public Cons(int elem, List next) {
this.elem = elem;
this.next = next;
}
public boolean empty(){
return false;
}
public int first(){
return elem;
}
#Override
public int count() {
if(elem>NEXT) {
return 1 + next.count();
}else {
return next.count();
}
}
```![enter image description here](https://i.stack.imgur.com/kWo0v.jpg)
The following code will create a recursive list with N elements with N value being defined by the size of the amount of elements found in the int array called elements in RecursiveList class. Call the startRecursion() method to create a recursive list with the defined elements and call count() to get the amount of elements in the array that are immediately followed by a lower number.
Main Class
This your application entry point:
public static void main(String[] args) {
int count = RecursiveList.startRecursion().count();
System.out.printf("List has %d recursive elements", count);
}
RecursiveList Class
abstract class RecursiveList {
protected static int index = -1;
protected static int[] elements = new int[]{ 5,2,1,4,3,2,6 };
public static RecursiveList startRecursion() {
return new Cons();
}
public abstract boolean empty();
public abstract int count();
public abstract Integer getElement();
public static int incIndex() {
return index += 1;
}
}
Cons Class
public class Cons extends RecursiveList {
private static int result;
private final Integer elem;
private final RecursiveList prev;
private final RecursiveList next;
private Cons(Cons parent) {
prev = parent;
elem = incIndex() < elements.length ? elements[index] : null;
System.out.printf("Creating new Cons with element %d(%d)%n", elem, index);
next = elem != null ? new Cons(this) : null;
}
Cons() {
this(null);
}
public boolean empty() {
return false;
}
#Override
public /*#Nullable*/ Integer getElement() {
return elem;
}
#Override
public int count() {
if (elem != null)
{
if (prev != null && elem < prev.getElement())
result += 1;
if (next != null) {
return next.count();
}
}
return result;
}
}
EDIT
Alright here is the answer you were actually looking for. This completely conforms to the limitations imposed on this exercise that you provided. The solution uses pure Java, neither the class nor any of it's method or field declarations were modified in any way and no such new elements were added. I've only added the implementation where the exercise said you should.
Main Class
public static void main(String[] args) {
List l = new Cons(3, new Cons(2,new Cons(1, new
Cons(4, new Cons(1, new Nil())))));
assert l.count() == 3;
l = new Cons(5, new Nil());
assert l.count() == 0;
l = new Cons(5, new Cons(5, new Cons(0, new Nil())));
assert l.count() == 1;
l = new Cons(5, new Cons(0, new Cons(5, new Cons(3, new Nil()))));
assert l.count() == 2;
System.out.println("All tests completed successfully!");
}
Cons Class
import java.util.NoSuchElementException;
public class Cons extends List {
private int elem;
private List next;
public Cons(int elem, List next) {
this.elem = elem;
this.next = next;
}
public boolean empty()
{ return false; }
public int first()
{ return elem; }
public int count()
{
try {
if (first() > next.first()) {
return 1 + next.count();
}
else return next.count();
}
catch (NoSuchElementException e) {
return 0;
}
}
}
Nil Class
import java.util.NoSuchElementException;
public class Nil extends List {
public boolean empty()
{ return true; }
public int first()
{ throw new NoSuchElementException(); }
public int count()
{
throw new IllegalAccessError();
}
}
public int NEXT(){
if(next!=null)
return next.first()
else
throw new Exception("No next element")
}

Remove every nth employee doesn't work

import java.util.LinkedList;
import java.util.List;
import java.util.ListIterator;
public class vijftienpunt1 {
public static void downsize(LinkedList<String> employeeNames, int n) {
for (int i = 0; i < employeeNames.size(); i++) {
if(i%n==0) {
employeeNames.remove(i);
}
}
}
public static void main(String[] args) {
LinkedList<String> employeeNamess = new LinkedList<String>();
employeeNamess.add("Ab");
employeeNamess.add("Yo");
employeeNamess.add("Ik");
employeeNamess.add("Jij");
System.out.println(employeeNamess);
downsize(employeeNamess, 2);
System.out.println(employeeNamess);
}
}
When I run this doesn't work, it removes other nth elements, how can I fix this. I have tried more operations but it still doesn't work
Use Iterator whenever you want to remove elements from list.
try below code:
public static void downsize(LinkedList<String> employeeNames, int n) {
int i=1;
Iterator<String> iter=employeeNames.iterator();
while(iter.hasNext()){
iter.next();
if(i%n==0) {
iter.remove();
}
i++;
}
}

"The method from ... is never used locally" on a public method inside an anonymous class

I'm implementing the iterable interface and returning the iterator using anonymous class.
The problem is I can't use my custom add from the anonymous class in the main method.
I can't call the add method in the main method.
Eclipse complains that it's not defined.
What is the problem?
I'll spare from you the outer class and just show you the method iterator:
#Override
public Iterator<Symbol> iterator() {
return new Iterator<Symbol>() {
int i = 0; //Remove i and it works. WHY?!!
public boolean hasNext() {
return i < symArr.length && symArr[i] != null;
}
public Symbol next() {
if (hasNext()) {
return symArr[i++];
}
return null;
}
public void add(Symbol addMe) {
if (i < symArr.length) {
symArr[i] = addMe;
}
}
};
}
My main method inside the outer class:
public static void main(String[] args) {
SymbolTable st = new SymbolTable(22);
Iterator<Symbol> it = st.iterator();
it.next();
it.add(new Symbol("2", 2)); //Have problem here.
//Problem disappears when I completely remove i variable in the iterator method.
}
The whole code:
package tirgul_iteratorsExceptions;
import java.util.Iterator;
public class SymbolTable implements Iterable<Symbol> {
Symbol[] symArr;
public SymbolTable(int size) {
symArr = new Symbol[size];
}
public SymbolTable(SymbolTable st, boolean isDeep) {
symArr = new Symbol[st.symArr.length];
if (isDeep) {
for (int i = 0; i < st.symArr.length; i++) {
symArr[i] = new Symbol(st.symArr[i].name, st.symArr[i].value);
}
}
// Shallow copy
else {
for (int i = 0; i < st.symArr.length; i++) {
symArr[i] = st.symArr[i];
}
}
}
#Override
public Iterator<Symbol> iterator() {
return new Iterator<Symbol>() {
int i = 0;
public boolean hasNext() {
return i < symArr.length && symArr[i] != null;
}
public Symbol next() {
if (hasNext()) {
return symArr[i++];
}
return null;
}
public void add(Symbol addMe) {
if (i < symArr.length) {
symArr[i] = addMe;
}
}
};
}
public static void main(String[] args) {
SymbolTable st = new SymbolTable(22);
Iterator<Symbol> it = st.iterator();
it.next();
it.add(new Symbol("2", 2));
}
}

Cannot instantiate the type Deque

import java.awt.HeadlessException;
import java.util.Iterator;
import java.util.NoSuchElementException;
import javax.xml.soap.Node;
public class Deque<Item> implements Iterable<Item> {
private int size;
private Node<Item> head;
private Node<Item> tail;
private static class Node<Item> {
private Item key;
private Node<Item> leftNode;
private Node<Item> rightNode;
Node(Item key, Node<Item> left, Node<Item> right) {
this.key = key;
this.leftNode = left;
this.rightNode = right;
}
}
public Deque() {
head = new Node<Item>(null,null,null);
tail = new Node<Item>(null,head,null);
head.rightNode = tail;
size = 0;
}
public boolean isEmpty() {
return head.rightNode == tail;
}
public int size() {
return size;
}
public void addFirst(Item item) {
if (item == null) throw new NullPointerException(" trying to add nothing");
else {
Node<Item> oldFirstNode = head.rightNode;
head.rightNode = new Node<Item>(item,head,oldFirstNode);
oldFirstNode.leftNode = head.rightNode;
size++;
}
}
public void addLast(Item item) {
if (item == null) throw new NullPointerException(" trying to add nothing");
else {
Node<Item> oldLastNode = tail.leftNode;
tail.leftNode = new Node<Item>(item,oldLastNode,tail);
oldLastNode.rightNode = tail.leftNode;
size++;
}
}
public Item removeFirst() { // remove and return the item from the front
if (isEmpty()) throw new NoSuchElementException(" Deque is alrady empty");
else {
Node<Item> delete = head.rightNode;
Node<Item> newFirstNode = head.rightNode.rightNode;
newFirstNode.leftNode = head;
head.rightNode = newFirstNode;
delete.leftNode = null;
delete.rightNode = null;
Item myKeyItem = delete.key;
delete = null;
size--;
return myKeyItem;
}
}
public Item removeLast() { // remove and return the item from the end
if (isEmpty()) throw new NoSuchElementException(" Deque is alrady empty");
else {
Node<Item> delete = tail.leftNode;
Node<Item> newLastNode = tail.leftNode.leftNode;
newLastNode.rightNode = tail;
tail.leftNode = newLastNode;
delete.leftNode = null;
delete.rightNode = null;
Item myKeyItem = delete.key;
delete = null;
size--;
return myKeyItem;
}
}
public Iterator<Item> iterator() { // return an iterator over items in order from front to end
return new DequeIterator();
}
private class DequeIterator implements Iterator<Item> {
private Node<Item> current = head.rightNode;
public boolean hasNext() {return current != tail;}
public void remove() { throw new UnsupportedOperationException("not yet"); }
public Item next() {
if (!hasNext()) throw new NoSuchElementException("no next");
Item key = current.key;
current = current.rightNode;
return key;
}
}
public static void main(String[] args) {
Deque<Integer>[] s = new Deque[10];
for (int i = 0; i < 10; i++) {
s[i] =new Deque<Integer>(); // initial each object
}
s[0].addFirst(1);
// s[1].addFirst(2);
StdOut.print(s[0]);
//StdOut.print(s[1]);
}
}
In the following code I have a compiling error stats that "Cannot instantiate the type Deque".
package Assign3;
import java.util.Deque;
public class graph {
//private Deque<Integer>[] graphRepDeques;
final static int Amount = 200;
private Deque<Integer>[] s = new Deque[Amount];
public graph(String filename) {
In in = new In(filename);
//final int Amount = 200;
s = new Deque[Amount];
for (int i = 0; i < Amount; i++) {
String[] currentLine = in.readLine().split("\\s");
int size = currentLine.length;
s[i] =new Deque<Integer>(); // why Cannot instantiate the type Deque<Integer>???????
for (int j = 1; j < size; j++) {
int temp = Integer.parseInt(currentLine[j]);
s[i].add(temp);
}
}
}
private void show() {
for (int i = 0; i < Amount; i++) {
for (int a: s[i]) {
//StdOut.print(a + " ");
}
}
}
public static void main(String[] args) {
graph a = new graph("kargerMinCut.txt"); //whatever text you like with integers
a.show();
}
}
The error I got is
Cannot instantiate the type Deque<Integer>
I can instantiate Deque in the main function in class "Deque", but why I cannot do it in class "graph"? Very confused here
I appreciate any help thanks.
The goal of my code is to read the numbers
in a file line by line and for each line,
I store the numbers I got into a object of class Deque.
Therefore, I need an array of objects
of Deque to store all the numbers.
Similary to an array of linkedlist (Deque in my code).
The problem is I do not know how to initialized an array of this linkedlist (Deque in my code) properly so I can "push" all the keys in each linkedlist (Deque)
Since you applied Codebender's hint, you now just have to replace
s[i] = new Deque<Integer>();
with:
s[i] = new LinkedList<Integer>();
as you already mentioned in your question.
java.util.Deque is only an interface and therefore cannot be instantiated directly. All your variables (including the array) can still be of the type Deque and Deque[] respectively, since java.util.LinkedList implements that interface.
In your edited code, the problem is that you are just initializing the array. Not the Deque objects.
Deque<Integer>[] s = new Deque[10];
The above just creates an Array of 10 elements (and initializes all of them to null).
Hence s[0] is null, just like any other index. And you are trying to call addFirst(1) on null element.
So you should be initalizing each element in the array before using them,
s[i] = new Deque(); // In a loop if needed.

Categories

Resources