Re: Beginner Projects



Pseudo Silk Kimono wrote:
public class IsPrime {
public static void main(String [] args) {
MyNumber m1 = new MyNumber(123);
System.out.println(m1.intValue + " " + m1.isPrime + " " + m1.isEven);

Style note: declare the members private and use the accessor methods.

}
}

public class MyNumber {
int intValue;
boolean isPrime;

For lazy evaluation, consider Boolean instead of boolean.

The JavaBean convention relates a [Bb]oolean variable "foo" to cover methods "isFoo()" and "setFoo()"; the variable isn't named "isFoo".

boolean isEven;
public MyNumber(int intValue) {
this.intValue = intValue;
this.isPrime = primeTester(intValue);

this is really too much work for a constructor. You might consider having these methods use lazy evaluation. (Use Boolean so that null serves as a marker value.)

if ( (intValue % 2) == 0 )
this.isEven = true;
else
this.isEven = false;

Better style: even = ((intValue % 2) == 0);

}
public int getIntValue() {

The trouble with names like "intValue" is you might decide to refactor the value as, say, long.

return intValue;
}
public void setIntValue(int intValue) {
this.intValue = intValue;
}
public boolean isPrime() {
// return isPrime;

if ( prime == null )
{
prime = primeTester( value );
}
return prime;

}

public static boolean primeTester( int candidate ) {
if ( candidate == 2) {
return true;
}
// if ( candidate == 1 | candidate == 0) {

What about negative numbers?

if ( candidate < 2 || (candidate & 0x01) == 0 )
{ // can't use isEven() because it's an instance value
return false;
}
// int y = 2;

You've already checked even values.

// while ( y < candidate ) {

That would go quicker if you only checked y < (int) Math.sqrt( candidate ).

A for() loop is more natural here.

for( int divisor = 3, limit = (int) Math.sqrt( candidate );
divisor <= limit; divisor += 2 ) // don't need to check even numbers
{
if ( (candidate % y) == 0 )
{ // don't forget your braces
return false;
}
// y++;
}
return true;
}
}

--
Lew
.