Java黑皮书课后题第10章:10.3(MyInteger类)设计一个名为MyInteger的类
生活随笔
收集整理的這篇文章主要介紹了
Java黑皮书课后题第10章:10.3(MyInteger类)设计一个名为MyInteger的类
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
10.3(MyInteger類)設計一個名為MyInteger的類
- 題目
- 程序說明
- 代碼
- Test3.java
- Test3_MyInteger.java
- 運行實例
- UML
題目
程序說明
測試程序:Test3.java
構造程序:Test3_MyInteger.java
代碼
Test3.java
public class Test3 {public static void main(String[] args) {Test3_MyInteger mi = new Test3_MyInteger(1);System.out.println(mi.getValue());System.out.println(mi.isEven() + " " + mi.isOdd() + " " + mi.isPrime());System.out.println(Test3_MyInteger.isEven(2) + " " + Test3_MyInteger.isOdd(2) +" " + Test3_MyInteger.isPrime(2));Test3_MyInteger mi_pro = new Test3_MyInteger(2);System.out.println(Test3_MyInteger.isEven(mi_pro) + " " + Test3_MyInteger.isOdd(mi_pro) +" " + Test3_MyInteger.isPrime(mi_pro));char[] ch = {'1', '2', '3'};System.out.println(Test3_MyInteger.parseInt(ch));String str = "123";System.out.print(Test3_MyInteger.parseInt(str));} }Test3_MyInteger.java
public class Test3_MyInteger {// int型數據域static int value;// 有參構造方法public Test3_MyInteger(int num){value = num;}// 獲取valuepublic int getValue() {return value;}// 三個方法,判斷對象中的值public boolean isEven(){return value % 2 == 0;}public boolean isOdd(){return value % 2 == 1;}public boolean isPrime(){return havePrimeNumber(value);}// 判斷指定值(int型)public static boolean isEven(int num){return num % 2 == 0;}public static boolean isOdd(int num){return num % 2 == 1;}public static boolean isPrime(int num){return havePrimeNumber(value);}// 判斷指定值(MyInteger型)public static boolean isEven(Test3_MyInteger mi){return mi.isEven(mi.value);}public static boolean isOdd(Test3_MyInteger mi){return mi.isOdd(mi.value);}public static boolean isPrime(Test3_MyInteger mi){return havePrimeNumber(mi.value);}// +: 判斷一個數是否是素數public static boolean havePrimeNumber(int num){boolean bool = true;for (int i = 2 ; i <= num / 2 ; i++){if (num % i != 0){bool = false;}}return bool;}// 判斷值是否相等public boolean equals(int num){return value == num;}public boolean equals(Test3_MyInteger mi){return this.value == mi.value;}// 數組字符構成的數組轉為int值public static int parseInt(char[] arr){int length = arr.length;String str = "";for (int i = 0 ; i < length ; i++){str += arr[i];}return parseInt(str);}// 字符串轉intpublic static int parseInt(String str){int length = str.length(), result = 0;char temp;for (int i = 0 ; i < length ; i++){temp = str.charAt(i);result = result * 10 + temp - 48;}return result;} }運行實例
1 false true true true false true true false true 123 123UML
與50位技術專家面對面20年技術見證,附贈技術全景圖總結
以上是生活随笔為你收集整理的Java黑皮书课后题第10章:10.3(MyInteger类)设计一个名为MyInteger的类的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Java黑皮书课后题第10章:10.2(
- 下一篇: Java黑皮书课后题第10章:10.4(