Using toString() form the Object class in java - java

import java.util.*;
public class MyStack {
private ArrayList<Object> list = new ArrayList<>();
public boolean isEmpty(){
return list.isEmpty();
}
public int getSize(){
return list.size();
}
public Object peek(){
return list.get(getSize()-1);
}
public Object pop(){
Object o = list.get(getSize() -1 );
list.remove(getSize() -1);
return o;
}
public void push(Object o ){
list.add(o);
}
#Override
public String toString() {
return "stack: " + list.toString();
}
public static void main(String[] args){
MyStack mystack = new MyStack();
mystack.push(mystack);
System.out.println(mystack.isEmpty());
System.out.println( mystack.getSize());
System.out.println( mystack.peek());
System.out.println(mystack.pop());
System.out.println(mystack.toString());
}
}
the problem is when I run this code I get a lot of exceptions and its because of the toString() method, and I don't know what is the problem can you help?

Related

Java ListStack<A> push and pushAll() method

We have a Liststack and an ADTStackJqwikTest.
Here's my code in ListStack for the push and the pushAll() method.
#Override
public Stack<A> push(A e) {
return new ListStack(list.cons(e));
}
#Override
public Stack<A> pushAll(List<A> xs) {
return xs.isEmpty() ? this : new ListStack<A>(List.append(xs, list));
}
In my ListStack I've a test:
public static void main(String[] args) {
Stack<Integer> s1 = empty();
s1 = s1.pushAll(list(1,2,3));
s1 = s1.pushAll(list(1,2,3));
System.out.println("PushAll: " + s1.toList());
Stack<Integer> s2 = empty();
s2 = s2.push(1);
s2 = s2.push(2);
s2 = s2.push(3);
s2 = s2.push(1);
s2 = s2.push(2);
s2 = s2.push(3);
System.out.println("Push: " + s2.toList());
}
}
the result I get is:
PushAll: 1, 2, 3, 1, 2, 3
Push: 3, 2, 1, 3, 2, 1
But the result should be the same. What do I wrong?
In my ADTStackJqwikTest I've to pushAll() methods.
// ∀s:Stack<A> : pushAll([],s) = s
#Property
<A> boolean pushAll(#ForAll("stacks") Stack<A> s) {
return s.pushAll(List.list()).equals(s);
}
// ∀s:Stack<A>, ∀xs:List<A> : pushAll(x:xs,s)= push(x,pushAll(xs,s)), falls s nicht leer
#Property
<A> boolean pushAll(#ForAll("stacks") Stack<A> s, #ForAll("lists") List<A> xs, #ForAll("as") A x) {
return s.pushAll(xs.cons(x)).equals(s.push(x).pushAll(xs));
}
package stack;
import list.List;
import tuple.Tuple;
import static list.List.list;
public class ListStack implements Stack {
private final List<A> list;
private ListStack(List<A> list) {
this.list = list;
}
private ListStack() {
this.list = list();
}
#Override
public boolean isEmpty() {
return list.isEmpty();
}
#Override
public Stack<A> push(A e) {
return new ListStack<A>(list.cons(e));
}
#Override
public Stack<A> pop() {
if(isEmpty())
throw new IllegalStateException("pop from an empty stack");
else return new ListStack<A>(list.tail());
}
#Override
public A top() {
if(isEmpty())
throw new IllegalStateException("top from an empty stack");
else return list.head();
}
#Override
public Tuple<A, Stack<A>> popTop() {
return Tuple.tuple(top(), pop());
}
#Override
public Tuple<List<A>, Stack<A>> popTopAll() {
return null;
}
#Override
public Stack<A> pushAll(List<A> xs) {
return xs.isEmpty() ? this : new ListStack<A>(List.append(xs, list));
}
#Override
public List<A> toList() {
return list;
}
#Override
public boolean isEqualTo(Stack<A> s) {
return this.toList().isEqualTo(s.toList());
}
#Override
public boolean equals(Object o) {
return o instanceof Stack && isEqualTo((Stack) o);
}
public String toString() {
return list.toString();
}
public static <A> Stack<A> empty() {
return new ListStack(list());
}
This is my whole ListStack
change
#Override
public Stack<A> pushAll(List<A> xs) {
return xs.isEmpty() ? this : new ListStack<A>(List.append(xs, list));
}
into
#Override
public Stack<A> pushAll(List<A> xs) {
return xs.isEmpty() ? this : new ListStack<A>(List.append(list, xs));
}
Okay I got it. Thank you guys.
The mistake was the append in the pushAll method.

What is wrong with this code? It won't run

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());
}
}

Reverse a stack using only queue in Java?

I need to loop through the stack until it is empty, adding each element to the queue. Then do the opposite. Loop through the queue until it is empty, adding each element back onto the stack
public class Q1 {
public static void reverseStack(Stack st){
}
}
Here is my test:
public class Q1Test {
#Test
public void testQ1() {
Stack st = new Stack(5);
st.push("A");
st.push("B");
Q1.reverseStack(st);
assertEquals("A",(String) st.top());
}
}
I have been trying to do the Q1 code and never get it to succeed and always end up fail. Can anyone implement a methods as said above to make the Q1 test succeed please?
Here is a working example:
Q1.java
import java.util.ArrayList;
import java.util.List;
public class Q1 {
private List<String> list;
public Q1() {
list = new ArrayList<String>();
}
public String pop_front() {
if (!list.isEmpty()) {
String front = list.get(0);
for (int i = 0; i < list.size()-1; i++) {
list.set(i, list.get(i+1));
}
list.remove(list.size()-1);
return front;
} else {
return null;
}
}
public void push_back(String obj) {
list.add(obj);
}
public String front() {
if (!list.isEmpty()) {
return list.get(0);
} else {
return null;
}
}
public boolean isEmpty() {
return list.isEmpty();
}
public static void reverseStack(Stack stack) {
Q1 queue = new Q1();
while (!stack.isEmpty()) {
queue.push_back(stack.pop());
}
while (!queue.isEmpty()) {
stack.push(queue.pop_front());
}
}
}
A Stack class:
Stack.java
package com.dub;
import java.util.ArrayList;
import java.util.List;
public class Stack {
private List<String> list;
public Stack() {
list = new ArrayList<String>();
}
public String pop() {
if (!list.isEmpty()) {
String top = list.get(list.size()-1);
list.remove(list.size()-1);
return top;
} else {
return null;
}
}
public void push(String obj) {
list.add(obj);
}
public String top() {
if (!list.isEmpty()) {
return list.get(list.size()-1);
} else {
return null;
}
}
public boolean isEmpty() {
return list.isEmpty();
}
}
and now the test method:
public static void main(String[] args) {
Stack stack = new Stack();
stack.push("A");
stack.push("B");
stack.push("C");
System.out.println("top: " + stack.top());
Q1.reverseStack(stack);
System.out.println("top: " + stack.top());
}
It prints as expected:
top: C
top: A

Java: How to populate a variable in subclass?

So this is not a assignment but one of my lecture slide did not make it clear and when I try to code something similar myself, I run into a problem.
I can't figure out how to populate a variable that is in my subclass.
here's my test code thus far:
Implementation class:
import javax.swing.JOptionPane;
public class House {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
int count = 0;
room[] r = new room[3];
int option = JOptionPane.showConfirmDialog(null, "type");
if(option==0){
r[count]=new type();
r[count].setSize(25);
r[count].setType("Bedroom");
}
else if(option==1){
r[count] = new room();
r[count].setSize(25);
}
JOptionPane.showMessageDialog(null, r[count].toString());
}
}
Superclass:
public class room {
double size;
public room(){
}
public room(double size){
this.size=size;
}
public double getSize(){return this.size;}
public boolean setSize(double size){
if(size<0.0){
return false;
}
else{
return true;
}
}
public String toString(){
return "Room size: " + this.size;
}
}
Subclass:
public class type extends room {
String type;
public type(){
}
public type (double size, String type){
super(size);
this.type=type;
}
public String getType(){return this.type;}
public boolean setType (String type){
if(type.equals("")){
return false;
}
else{
return true;
}
}
public String toString(){
return super.toString() + "Room Type: " + this.getType();
}
}
when i try to run the code, if I tried to insert data into setType() method in type class, it would give me an error. Can someone please tell me where I am messing up? Thanks!
Remember the original pointer:
if(option==0){
type t = new type();
t.setSize(25);
t.setType("Bedroom");
r[count]= t;
}
Alternatively you can cast to original type:
((type) r[count]).setType("Bedroom");

Overriding value in heap java programming

I've added to my project a new data structure Heap<Integer,Integer> but the only problem I've got is that it prints me only one time the result.
If I have the input:
v=10;new(v,20);new(a,22);print(v)
at the end of execution
Heap={1->20, 2->22},
SymTable={v->1, a->2}
But what it gives me:
Heap: 1->22
SymTable: a -> 1
v -> 1
It overrides the first value.Here is the code from the controller where is the main part:
HeapAllocation crtStmt1=(HeapAllocation) crtStmt;
String varI = crtStmt1.getVarname();
Exp e = crtStmt1.getExpression();
int i=0;
Id<Object,Integer> tbl = state.getDict();
IHeap<Integer,Integer> heap1 = state.getHeap();
int value= e.eval(tbl, heap1);
heap1.put(++i, value);
if (tbl.containsKey(varI))
tbl.update(varI,i);
tbl.update(varI, i);
The problem I guess is after this line:
heap1.put(++i, value);
because for a new operation it doesn't append to the previous one, just overrides it.
Edit:
The implementation of the heap:
public class Heap<Integer,In> implements IHeap<Integer, Integer>,Serializable{
private Map<Integer, Integer> mapp;
public Heap(){
mapp = new HashMap<Integer,Integer>();
}
public void put(Integer index, Integer value){
mapp.put(index, value);
}
public void remove(Integer index){
try{
if(isEmpty())
throw new ExceptionRepo();
else
mapp.remove(index);
}catch (ExceptionRepo ex){
System.err.println("Error: Heap is empty.");
}
}
public boolean isEmpty(){
return mapp.isEmpty();
}
public Integer get(Integer index){
return mapp.get(index);
}
public boolean containsIndex(Integer index){
return mapp.containsKey(index);
}
public void update(Integer index, Integer value){
mapp.put(index, value);
}
public String toString(){
Set<Integer> all = mapp.keySet();
Object[] keysA= all.toArray();
String res="";
for(int i=0; i<mapp.size(); i++){
Integer v = mapp.get(keysA[i]);
res += keysA[i].toString() + "->" + v.toString() + "\r\n";
}
return res;
}
}
Edit2: Maybe the problem is in the eval function implementation.To be clear, I have a Exp class:
public class Exp{
public int eval(Id<Object,Integer> tbl)throws ExceptionRepo{
return 0;
}
public String toString(){
return "";
}
public int eval(Id<Object,Integer> tbl,IHeap<Integer,Integer> heap) throws ExceptionRepo{
return 0;
}
And some derived classes that extends the Exp class.I added a new method in the ConstExp class:
public class ConstExp extends Exp implements Serializable{
int number;
public int eval(Id<Object,Integer> tbl) throws ExceptionRepo{
return number;
}
public ConstExp(int n){
number = n;
}
public String toString(){
return "" + number;
}
public int eval(Id<Object,Integer> tbl,IHeap<Integer,Integer> heap) throws ExceptionRepo{
return number; //THIS IS THE NEW METHOD
}
This class should return a value..so for "v=20", after execution of the statement it puts the value 20 in the v based on this class implementation.
If it's useful this is the statement evaluation rule for the heap(that I implemented in the controller up there):
Stack1={new(var,exp)| Stmt2|...}
SymTable1
Heap1
==>
Stack2={Stmt2|...}
let be v=eval(exp,SymTable1,Heap1) in
Heap2 = Heap1 U {newfreelocation ->v}
if var exists in SymTable1 then SymTable2 = update(SymTable1,
var,newfreelocation)
else SymTable2 = add(SymTable1,var, newfreelocation)
How to resolve this?

Categories