Writing a size() method for a User-defined Stack Class - stack

I'm writing a program that requires the length/size of a stack. Because I am not importing the Stack class (and I've made my own - see below) I don't know how to make a method that calculates the size of the stack and returns that integer value. Here's the Stack class so far:
public class Stack<String> implements StackInter<String>
{
public void push(String x)
{ // This method is written
}
public String pop()
{ // This method is written
}
public boolean isEmptyStack()
{ // This method is written
}
public String peek()
{ // This method is written
}
public int size()
{
// What goes in here!
}
}
This is where I want to use the size method
public class InfixCalculator
{
Stack<String> stack = new Stack<String>();
int size = stack.size();
}
Any suggestions would be greatly appreciated!

the pseudo code is somthing like this:
public class Stack<String> implements StackInter<String>
{
private size;
//constructor
public Stack<String>(){
size=0;
}
public void push(String x)
{ // This method is written
size++;
}
public String pop()
{ // This method is written
if(size > 0 )
size--;
}
public boolean isEmptyStack()
{ // This method is written
}
public String peek()
{ // This method is written
}
public int size()
{
int theSize=size;
return theSize;
}
}
after you apply your operations the size can be computed.

If your Stack is an array write
public int size() {
return array.length;
}

Related

I want to know, in the code provided what does 'this' keyword referring to.?

/*
I know this keyword is used to refer to class members but i am unable to understand what does 'this'.isEmpty() referring to. Some class ? class method? Or some variable?
For example:
this.value = value;
I understand that here, this.value is referring to class variable value but not for previous occurence of 'this'.
*/
public class StackWithMin extends Stack< NodeWithMin > {
public void push(int value) {
int newMin = Math.min(value, min());
super.push(new NodeWithMin(value,newMin));
}
public int min() {
if(this.isEmpty()) {
return Integer.MAX_VALUE; // Error value
} else {
return peek().min;
}
}
}
class NodeWithMin {
public int value;
public int min;
public NodeWithMin(int value, int min) {
this.value = v;
this.min = min;
}
}
"this" here is object of the class StackWithMin which is extending Stack class from java.util. so StackWithMin is instance of Stack class.
this.isEmpty() which is method defined in Stack, here checks if the stack has any element or not. if it has zero element it returns true else false.
Hope it clears your doubt.

How to return value from unit test?

I have the following problem.I have a process that is done in 3 steps:
Step 1 -> Step 2 ->Step 3
I want to be able to test all combinations.
Step1
Step1+Step2
Step2
Step2+Step3
Step1+Step2+Step3
In order to do this i would like to be able to return something from each of my Unit Tests.
I do not want to create global variables and mutate them every single time.
class TestPipeline
{
[Testcase]
public Int Step1()
{
////do something
Int outputStep1=doSomeStuff();
return outputStep1;
}
[Testcase]
public Int Step2()
{
Int inputStep1=Step1();
Int outputStep2=doSomething(inputStep1);
return outputStep2;
}
[Testcase]
public void Step3()
{
Int inputStep2=Step2();
Int result=doSomethingElse(inputStep2);
}
}
How can this be done ?
It sounds to me that you need helper methods that you can reuse, you're most of the way there, just need to extract out the methods.
As for getting the combinations correct I'd just hard-code the combinations. It looks like your steps are sequential so there won't be such a test as Step2+Step3 because it would really be Step1+Step2+Step3.
Tests are normally data driven and having logic in the test to vary behaviour based on data with something such as Combinatorial adds unwanted logic into the test.
class TestPipeline
{
private int doSomeStuff()
{
return someStuff;
}
private int doSomething(int someStuff)
{
return something;
}
private int doSomethingElse(int something)
{
return somethingElse;
}
[Testcase]
public void Step1()
{
////do something
int outputStep1 = doSomeStuff();
return outputStep1;
}
[Testcase]
public void Step1Step2()
{
int inputStep1 = doSomeStuff();
int outputStep2 = doSomething(inputStep1);
return outputStep2;
}
[Testcase]
public void Step1Step2Step3()
{
int inputStep1 = doSomeStuff();
int outputStep2 = doSomething(inputStep1);
int result = doSomethingElse(inputStep2);
}
}

Binding between an Object and a SimpleIntegerProperty

I have a combo box over my GUI in JavaFX.
This Combo Box is composed of a complex type elements :
public class DureeChoiceBoxElement extends ObservableValueBase<DureeChoiceBoxElement> {
private IntegerProperty duree;
#Override
public String toString() {
return duree.get() + " an";
}
}
I want to map (or bind) the selected complex element with my model which contains the simple type :
public class Pel {
private IntegerProperty duree = new SimpleIntegerProperty(1);
public Property<Number> dureeProperty() {
return duree;
}
public void setDuree(Integer duree) {
this.duree.setValue(duree);
}
public Integer getDuree() {
return duree.getValue();
}
}
How to do it ?
I tried in the controller with :
public class PelController {
#FXML
private ChoiceBox<DureeChoiceBoxElement> duree;
//etc..
pel.dureeProperty().bind(createElapsedBindingByBindingsAPI2(duree.getValue()));
/*
* #return an ObjectBinding of immutable TimeElapsed objects for the player
*/
private ObjectBinding<Property<Number>> createElapsedBindingByBindingsAPI2(
final DureeChoiceBoxElement dureeChoiceBoxElement) {
return Bindings.createObjectBinding(new Callable<Property<Number>>() {
#Override
public IntegerProperty call() throws Exception {
return dureeChoiceBoxElement.dureeProperty();
}
}, dureeChoiceBoxElement.dureeProperty());
}
}
But it doesn't work (even not compile). I want to say that "Bind this simple property to this complex Object calling the method I give you through the method named "createElapsedBindingByBindingsAPI2(..)".
It is logical read but I didn't managed to make it works anyway.
That's poor ....
Any help please :).
Example that (obviously) works with legacy code style (Swing coding) :
duree.getSelectionModel().selectedItemProperty().addListener(new ChangeListener<DureeChoiceBoxElement>() {
#Override
public void changed(ObservableValue<? extends DureeChoiceBoxElement> observable,
DureeChoiceBoxElement oldValue, DureeChoiceBoxElement newValue) {
// changement durée
log.debug("Durée sélectionnée : {}", duree.getSelectionModel().getSelectedItem().getDuree());
log.debug("Durée bindée ? : {}", pel.getDuree());
pel.setDuree(duree.getSelectionModel().getSelectedItem().getDuree());
}
});
Like this my model is set to selected item. But it implies some boilerplate code. Any better idea based on high level bindings of JavaFX ?

How to implement Iterable<E>

I am trying to port the Java code below to Dart and am puzzled about to do this.
In Java the Iterable interface is where clean with one method and to implement this is a snap.
How is this code best transformed to Dart?
/**
* Chess squares represented as a bitmap.
*/
public class ChessSquares implements Iterable<ChessSquare> {
private static class ChessSquaresIterator implements Iterator<ChessSquare> {
long bits;
int nextBit;
public ChessSquaresIterator(long bits) {
this.bits = bits;
nextBit = Long.numberOfTrailingZeros(bits);
}
#Override
public boolean hasNext() {
return (nextBit < 64);
}
#Override
public ChessSquare next() {
ChessSquare sq = ChessSquare.values()[nextBit];
bits = bits & ~sq.bit;
nextBit = Long.numberOfTrailingZeros(bits);
return sq;
}
#Override
public void remove() {
throw new UnsupportedOperationException();
}
}
#Override
public Iterator<ChessSquare> iterator() {
return new ChessSquaresIterator(bits);
}
...
By using IterableMixin you only need to implement the iterator-function.
class ChessSquares with IterableMixin<ChessSquare> {
#override
Iterator<ChessSquare> get iterator => new ChessSquaresIterator(bits);
...
}
Visit http://blog.sethladd.com/2013/03/first-look-at-dart-mixins.html for a short introduction on mixins.
The Iterator-interface is straight forward. You only have to implement the function moveNext and the getter current.
Soo I tried this which is kind of not what I want since I do not want to extend a base class.
/**
* Chess squares represented as a bitmap.
*/
class ChessSquares extends IterableBase<ChessSquare> {
Iterator<ChessSquare> get iterator {
return new ChessSquaresIterator(this);
}
...
}
class ChessSquaresIterator extends Iterator<ChessSquare> {
int _nextBit;
int64 _bits;
ChessSquare _current;
ChessSquaresIterator(ChessSquares squares) {
_bits = new int64.fromInt(squares._bits);
}
bool moveNext() {
_nextBit = _bits.numberOfTrailingZeros();
if (_nextBit < 64) {
_current = ChessSquare.values()[_nextBit];
_bits = _bits & ~_current.bit();
} else {
_current = null;
}
return _nextBit < 64;
}
E get current => _current;
}

a last in, first out (LIFO) abstract data type and data structure. Perhaps the most common use of stacks is to store

MyStack()
{
Vector<Integer> v=new Vector<Integer>(10,2);
}
void push(int n)
{
v.addElement(n);
}
void pop()
{
if(v.isEmpty())
System.out.println("Stack underflow!");
else
System.out.println(v.elementAt(0));
}
void display()
{
for(int i=0;i<v.size();i++)
System.out.print(v.elementAt(i) +" ");
}
}
class StackDemo
{
public static void main(String args[])
{
Scanner in=new Scanner(System.in);
MyStack s=new MyStack();
int option=0;
do
{
System.out.println("1: Push\n2:Pop\n3:Display\n4:Quit");
System.out.println("Enter your option: ");
option=in.nextInt();
switch(option)
{
case 1:
{
System.out.println("Enter an integer:");
int n=in.nextInt();
s.push(n);break;
}
case 2:s.pop();break;
case 3:s.display();break;
}
}
while(option!=4);
}
}
// throws an error: variable v not found. Any help would be much appreciated.Thanks.
It looks like v is being created locally in your constructor instead of as a member of your class.
Try defining v as a class member and then simply assign it in your constructor.
class MyStack {
Vector<Integer> v;
public MyStack() {
v = new Vector<Integer>(10,2);
}
}
Or just assign it when you define it:
class MyStack {
Vector<Integer> v = new Vector<Integer>(10,2);
}
Check out the Java tutorial on class members.

Resources