一、類圖
?
二、代碼
package application;
public class Commission {
/*
* hp:耳機 80元 mpc:手機殼 10元 cpsp:手機貼膜 8元
*/
public float calculate(String line) {
int hp = 0, mpc = 0, cpsp = 0;
String[] input = null;
float money = 0;
while (true) {
// 【去掉字符串前后的空格】
line = line.trim();
// 【去掉字符串中多余的空格】
line = line.replaceAll("\\s{1,}", " ");
input = line.split(" ");
if (Judge(input)) {
// 判斷是否不小于0
if ((hp = Integer.parseInt(input[0])) < 0) {
System.out.println("輸入數量不滿足要求");
return -1;
}
if ((mpc = Integer.parseInt(input[1])) < 0) {
System.out.println("輸入數量不滿足要求");
return -1;
}
if ((cpsp = Integer.parseInt(input[2])) < 0) {
System.out.println("輸入數量不滿足要求");
return -1;
}
} else {
System.out.println("輸入數量不滿足要求");
return -1;
}
money = commission(hp, mpc, cpsp);
return money;
}
}
// 計算傭金
private static float commission(int hp, int mpc, int cpsp) {
float commission = 0;
int total = hp * 80 + mpc * 10 + cpsp * 8;
if (total < 1000) {
commission = (float) (total * 0.1);
} else if (total <= 1800) {
commission = (float) (1000 * 0.1 + (total - 1000) * 0.15);
} else {
commission = (float) (1000 * 0.1 + 800 * 0.15 + (total - 1800) * 0.2);
}
return commission;
}
// 判斷用戶輸入的是不是三個整數
private static boolean Judge(String[] input) {
String number = "0123456789";
// 判斷輸入的是不是三個字符串
if (input.length != 3) {
return false;
}
// 判斷三個字符串是不是純數字且不含小數點
for (int i = 0; i < 3; i++) {
for (int j = 0; j < input[i].length(); j++) {
if ("+".equals(String.valueOf(input[i].charAt(0))) || "-".equals(String.valueOf(input[i].charAt(0)))) {
if ("+".equals(String.valueOf(input[i].charAt(0)))) {
input[i].substring(1);
}
continue;
}
if (number.indexOf(input[i].charAt(j)) == -1) {
return false;
}
// 【判斷輸入的字符串是否大于整型的最大數值】
input[i] = input[i].replaceFirst("^0*", "");
if (Long.parseLong(input[i]) > Integer.MAX_VALUE || input[i].length() > 10) {
return false;
}
}
}
return true;
}
}
package application;
import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.stage.Stage;
public class Main extends Application {
@Override
public void start(Stage primaryStage) {
try {
Parent root = FXMLLoader.load(getClass().getResource("Main.fxml"));
primaryStage.setTitle("Calculate Commission");
primaryStage.setScene(new Scene(root));
primaryStage.show();
} catch (Exception e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
launch(args);
}
}
4、結果截圖
?