Thread: small piece of code: cannot set a max

1. Member
Join Date
Feb 2010
Posts
36
Rep Power
0

small piece of code: cannot set a max

hey everyone,
I am able of giving in a number as a maximum and a number that is supposed to be maximum the "max" that I have signed with the setMax. The only thing is that I can still set a number bigger then the maximum I've set.For exampe: I set the maximum using setMax to 50 and then set optel with setOptel tot 55 then optel will still return 55 instead of 0. This is the code:

public class Teller{

private int optel = 0;
private int max;

public Teller() {
}

public int getOptel(){
return optel; }
public int getMax() {
return max; }

public void setOptel(int optel){

*** here I want to limit "optel" to a maximum of the value "max" ***

if( optel >= 0 && optel <= this.getMax()) {
this.optel=optel;}
}
***setting a number***

public void setMax(int max) {
this.max=max;
}

public void telEenbij() {
this.optel=this.getOptel() + 1;
}

public void telAantalbij(int getal) {
this.optel=this.getOptel() + getal;
}

public void print() {
System.out.println("De totale waarde is : " + optel + " en het maximum dat u heeft aangegeven is : " + max);
}

public void vermenigvuldigMet(int getal) {
this.optel=this.getOptel() * getal;
}

public void reset() {
this.setOptel(0);
this.setMax(0); }

}

2. would you be calling the getOpTel() after you called setMax(),
for example, setOptel(), setMax(), getOptel()

Perhaps what I would do is to create an adjust() method that was invoked by any of the possible actions, such as from setting max and setting optel. This also has the advantage of keeping all of the business rules and validation kinds of things in one spot.

For example,
Java Code:
```public class Teller{

private int optel = 0;
private int max;

public Teller() {
}

public int getOptel(){
return optel;
}

public int getMax() {
return max;
}

public void setOptel(int optel) {
this.optel = optel;
}

public void setMax(int max) {
this.max=max;
}

/**
* Enforces the optel value to be within max.
* When the max >= 0, and the optel value is larger than max, make the optel value equal to the max value.
* (use max = -1 to disable max boundary).
*/
private void adjust() {
if (max >= 0 && this.optel > this.max) {
// optel is currently larger than max, adjust it.
this.optel=this.max
}

}

// the other methods here...
}```

Posting Permissions

• You may not post new threads
• You may not post replies
• You may not post attachments
• You may not edit your posts
•