第十章第三题(MyInteger类)(MyInteger class)
10.3(MyInteger类) 10.3(MyInteger class) 参考代码:
package chapter10;
public class Code_03 {
public static void main ( String[ ] args) {
MyInteger myInteger = new MyInteger ( 10 ) ;
System. out. println ( "Test getValue: " + myInteger. getValue ( ) ) ;
System. out. println ( "Test isEven: " + myInteger. isEven ( ) ) ;
System. out. println ( "Test isPrime: " + myInteger. isPrime ( ) ) ;
System. out. println ( "Test isOdd: " + myInteger. isOdd ( ) ) ;
System. out. println ( "Test equals(int): " + myInteger. equals ( 12 ) ) ;
System. out. println ( "Test equals(MyInteger): " + myInteger. equals ( new MyInteger ( ( 10 ) ) ) ) ;
System. out. println ( "Test static isEven: " + MyInteger. isEven ( 10 ) ) ;
System. out. println ( "Test static isOdd: " + MyInteger. isOdd ( 10 ) ) ;
System. out. println ( "Test static isPrime: " + MyInteger. isPrime ( 10 ) ) ;
System. out. println ( "Test statuc parseInt(char[]): " + MyInteger. parseInt ( new String ( new char [ ] { '1' , '2' , '3' , '4' } ) ) ) ;
System. out. println ( "Test static parseInt(String): " + MyInteger. parseInt ( "1234" ) ) ;
}
}
class MyInteger {
private int value;
MyInteger ( int value) {
this . value = value;
}
public int getValue ( ) {
return value;
}
public boolean isEven ( ) {
if ( value % 2 == 0 )
return true ;
return false ;
}
public boolean isOdd ( ) {
if ( ( value + 1 ) % 2 == 0 )
return true ;
return false ;
}
public boolean isPrime ( ) {
if ( value == 1 )
return false ;
for ( int i = 1 ; i < value; i++ )
if ( value % i == 0 )
return false ;
return true ;
}
public static boolean isEven ( int value) {
if ( value % 2 == 0 )
return true ;
return false ;
}
public static boolean isOdd ( int value) {
if ( ( value + 1 ) % 2 == 0 )
return true ;
return false ;
}
public static boolean isPrime ( int value) {
if ( value == 1 )
return false ;
for ( int i = 1 ; i < value; i++ )
if ( value % i == 0 )
return false ;
return true ;
}
public boolean equals ( int value) {
if ( this . value == value)
return true ;
return false ;
}
public boolean equals ( MyInteger myInteger) {
if ( this . value == myInteger. value)
return true ;
return false ;
}
public static int parseInt ( char [ ] chars) {
return Integer. parseInt ( chars. toString ( ) ) ;
}
public static int parseInt ( String string) {
return Integer. parseInt ( string) ;
}
}
Test getValue: 10
Test isEven: true
Test isPrime: false
Test isOdd: false
Test equals ( int ) : false
Test equals ( MyInteger) : true
Test static isEven: true
Test static isOdd: false
Test static isPrime: false
Test statuc parseInt ( char [ ] ) : 1234
Test static parseInt ( String) : 1234
Process finished with exit code 0