Reputation: 1546
I wrote the following constructor that gets 2 parameters and if a value (x or y) is negative, it will be initialize into zero.
public Point1 ( int x , int y )
{
//if one or more of the point values is <0 , the constructor will state a zero value.
if (x < 0)
{
_x = 0;
}
else
_x=x;
if (y < 0)
{
_y = 0;
}
else
_y = y;
}
I just need it to be minimalism if it can be...
Upvotes: 3
Views: 214
Reputation: 36
This is just for fun (no conditionals and of course not efficient at all). It does minimize if conditionals though :)
int temp = (x&(~Integer.MAX_VALUE))>>>(Integer.SIZE - 6);
_x = (x >>> (temp - (temp >> 5))) - (temp >> 5);
Slight improvement:
int temp = (x&(~Integer.MAX_VALUE))>>>(Integer.SIZE - 6);
_x = (x << (temp - (temp >> 5))) & Integer.MAX_VALUE;
Upvotes: 0
Reputation: 147154
What I'd actually prefer:
public Point1(int x, int y) {
this.x = nonnegative(x);
this.y = nonnegative(y);
}
where:
public static int nonegative(int value) {
if (value < 0) {
throw new IllegalStateException(
value + " is negative"
);
}
return value;
}
If you hide the constructor and add a static creation method, so much the better (if a little more verbose). Certainly a negative carpet-sweeping creation method shouldn't be munged into a constructor.
Upvotes: 0
Reputation: 13140
If you want to use the fewest characters possible, maybe something like:
public Point1(int x, int y) {
_x = Math.max(0,x);
_y = Math.max(0,y);
}
Upvotes: 1
Reputation: 30865
public Point1 ( int x , int y ) {
if(x < 0 ) x = 0;
if( y < 0) y = 0;
_x = x;
_y = y;
}
or
public Point1 ( int x , int y ) {
_x = x < 0 ? 0 : x;
_y = y < 0 ? 0 : y;
}
Upvotes: 0
Reputation: 19635
This might work for you:
public Point1 (int x, int y)
{
_x = x < 0 ? 0 : x;
_y = y < 0 ? 0 : y;
}
Upvotes: 1
Reputation: 39992
That code is as simple as it gets. If you're looking for cleaner code (and this depends on the developer) I always use ternary operators for simple if-else statements:
_x = (x < 0) ? 0 : x;
_y = (y < 0) ? 0 : y;
That just says that if x < 0, use 0, otherwise use x
Upvotes: 0
Reputation: 308021
_x = Math.max(0, x);
_y = Math.max(0, x);
or
_x = x < 0 ? 0 : x;
_y = y < 0 ? 0 : y;
Upvotes: 4
Reputation: 22818
Write a function, NegativeToZero
and use that instead:
_x = NegativeToZero(x);
_y = NegativeToZero(y);
Upvotes: 0