Define a primitive data type: Difference between revisions

→‎{{header|Java}}: Grammar fix, added convenience add and assign methods, simplified checkBounds
m (omit TI-BASIC)
(→‎{{header|Java}}: Grammar fix, added convenience add and assign methods, simplified checkBounds)
Line 503:
 
=={{header|Java}}==
The closest you can get to defining a primitive type in Java is making a new wrapper class for yourself with methods for math operations.
 
This example class throws an exception if the value is out of the bounds; it is implemented only in the assignment operatormethod "assign" and the addition method "add" operator. The class can be easily extended.
 
<lang java>class BoundedIntOutOfBoundsException extends Exception
Line 524:
}
 
private boolean checkboundscheckBounds(int v) {
ifreturn ( (v >= this.lower) && (v <= this.upper) ) {;
return true;
} else {
return false;
}
}
 
public void assign(BoundedInt i) throws BoundedIntOutOfBoundsException {{
assign(i.value()); //could still throw Exception if the other BoundedInt has different bounds
}
 
public void assign(int v) throws BoundedIntOutOfBoundsException {
if ( checkboundscheckBounds(v) ) {
this.value = v;
} else {
throw new BoundedIntOutOfBoundsException(v, this.lower, this.upper);
}
}
 
public int add(BoundedInt i) throws BoundedIntOutOfBoundsException {
return trueadd(i.value());
}
 
public int add(int i) throws BoundedIntOutOfBoundsException {
if ( checkboundscheckBounds(this.value + i) ) {
this.value += i;
} else {
Line 555 ⟶ 559:
 
 
public class boundedBounded {
public static void main(String[] args) throws BoundedIntOutOfBoundsException {
BoundedInt a = new BoundedInt(1, 10);
Anonymous user