再來練一遍,模擬鍵盤輸入數字,找出最大值和最小值
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 warn) {
BufferedReader buf = new BufferedReader(new InputStreamReader(System.in));
int num = 0;
String str = null;
boolean flag = true;
System.out.print(warn);
while(flag) {
try {
str = buf.readLine();
} catch (IOException e) {
e.printStackTrace();
}
if(str.matches("\\d+")) {
num = Integer.parseInt(str);
flag = false;
}else {
System.out.print("不是數字,重新輸入:");
}
}
return num;
}
}
package yn.ngems.cn.Iinterface;
public interface ICompareNumber {
public int [] getCompareNumbers(int count) ;
}
package yn.ngems.cn.IinterfaceImpl;
import yn.ngems.cn.Iinterface.ICompareNumber;
import yn.ngems.cn.util.InputUtil;
public class ICompareNumberImpl implements ICompareNumber{
public ICompareNumberImpl() {}
/**
* return data[2],最大值:data[0],最小值:data[1]
*/
@Override
public int[] getCompareNumbers(int count) {
int num [] = new int [count];
int data [] = new int [2];
for(int x = 0;x < num.length;x ++) {
num[x] = InputUtil.getNumber("請輸入第" + (x + 1) + "個數字:");
}
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.Iinterface.ICompareNumber;
import yn.ngems.cn.IinterfaceImpl.ICompareNumberImpl;
public class Factory {
public static ICompareNumber getInstance() {
return new ICompareNumberImpl();
}
}
package yn.ngems.cn.test;
import yn.ngems.cn.Iinterface.ICompareNumber;
import yn.ngems.cn.factory.Factory;
public class TestCompareNumberDemo {
public static void main(String[] args) {
ICompareNumber icNumber = Factory.getInstance();
int results [] = icNumber.getCompareNumbers(7);
System.out.println("最大值:" + results[0] + "、最小值:" + results[1]);
}
}