We have seen integer= -Integer.MAX_VALUE to
Integer.MAX_VALUE.
We may only want a small range of this : posint = 1 ..
Integer.MAX_VALUE
EX:
type less = 1..31
var j:less
i:integer
begin
j34 // compile error - not in range
i34 // OK
ji // OK at compile
end // Run time error - Scalar out of range
Very nearly the same!!
Contention as to whether the assignment should be picked
up as a compile time error or not.
class IntegerSubRange
{
// First the data and the constructor
// of this class
private int lowerBound;
private int upperBound;
private int value;
public IntegerSubRange(int lower, int upper)
{
lowerBound=lower;
upperBound=upper;
}
// methods for manipulating value indirectly.
public assignValue(int val)
{
if ( (val >=lowerBound) &&
(val <=upperBound) )
value = val;
else /* error */;
}
public int returnValue()
{
return(value);
}
} // end of class with data and methods.
and declare variable as:
IntegerSubRange j =
new IntegerSubRange(lower,upper);
What should we do with the error? What kind of thing can we
do?
public assignValue(int val) throws IllegalAccessException
{
if ( (val >=lowerBound) && (val <=upperBound) )
value = val;
else
throw new IllegalAccessException(
"Assigned value must be between " + lowerBound + " and " + upperbound + "inclusive");
}
We can use subranges of user defined or enumerated types as
below:
type colour = (red,orange,yellow,green,blue,indigo,violet);
roy = red .. yellow;
gbiv = green .. violet;
roygb = red .. blue;
workday = monday..friday;
Must define type before using