模擬輸入數字,找出最大值和最小值
package yn.ngems.cn.util; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; public class InputUtil {//數字輸入類 public static int getNumber(String prompt) throws IOException { BufferedReader buf = String str = null; boolean flag = true; int num = 0; while(flag) { System.out.print(prompt); str = buf.readLine(); if(str.matches("\\d+")) { num = Integer.parseInt(str); flag = false; }else { System. } } return num; } } package yn.ngems.cn.compare; import java.io.IOException; import yn.ngems.cn.interfaceNum.INumberCompare; import yn.ngems.cn.util.InputUtil; public class CompareNumber implements INumberCompare{ public CompareNumber() {} /** * int[2]兩個內容,0為最大值,1為最小值 * @return */ public int [] compareNum(int count) { int data [] = new int [2]; int num [] = new int[count]; for(int x = 0;x < num.length;x ++) { try { num[x] = InputUtil.getNumber("請輸入第" + (x + 1) + "數字:"); } catch (IOException e) { e.printStackTrace(); } } data[0] = num[0]; data[1] = num[0]; for(int x = 0;x < num.length;x ++) { if(num[x] > data[0]) { data[0] = num[x]; } if(num[x] < data[1]) { data[1] = num[x]; } } return data; } } package yn.ngems.cn.factory; import yn.ngems.cn.compare.CompareNumber; import yn.ngems.cn.interfaceNum.INumberCompare; public class FactoryNumber { public static INumberCompare getInstance() { return new CompareNumber(); } } package yn.ngems.cn.test; import java.io.IOException; import yn.ngems.cn.factory.FactoryNumber; import yn.ngems.cn.interfaceNum.INumberCompare; public class NumberTest { public static void main(String[] args) throws IOException { INumberCompare numcompare = FactoryNumber.getInstance(); int results [] = numcompare.compareNum(10); System.out.println("最大值:" + results[0] + "、最小值:" + results[1]); } } package yn.ngems.cn.interfaceNum; public interface INumberCompare { public int [] compareNum(int count); }
|