【发布时间】:2016-04-19 22:21:18
【问题描述】:
我创建了这个程序,它应该让用户从文本字段中输入贷款金额和贷款期限(以年为单位),它应该显示从 5% 到 8% 的每个利率的每月和总还款额,其中在文本区域中以八分之一为增量。这可能听起来很愚蠢,但不确定如何添加异常处理以在输入非数字值时添加异常处理。例如,用户输入 5 而不是输入 5 作为年数。应用程序应显示错误消息.提前致谢。 一揽子贷款;
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.stage.Stage;
import javafx.scene.control.Label;
import javafx.scene.control.TextField;
import javafx.scene.control.TextArea;
import javafx.scene.control.Button;
import javafx.scene.control.ScrollPane;
import javafx.scene.layout.HBox;
import javafx.scene.layout.BorderPane;
import javafx.geometry.Pos;
public class loan extends Application {
protected TextField tfLoanAmount = new TextField();
protected TextField tfNumberOfYears = new TextField();
protected TextArea textArea = new TextArea();
@Override // Override the start method in the Application class
public void start(Stage primaryStage) {
tfNumberOfYears.setPrefColumnCount(2);
tfLoanAmount.setPrefColumnCount(7);
textArea.setPrefColumnCount(30);
// Create a button
Button btShowTable = new Button("Show Table");
// Create a hbox
HBox paneForControls = new HBox(10);
paneForControls.setAlignment(Pos.CENTER);
paneForControls.getChildren().addAll(new Label("Loan Amount"), tfLoanAmount,
new Label("Number of Years"), tfNumberOfYears, btShowTable);
// Create a scrollPane
ScrollPane scrollPane = new ScrollPane(textArea);
// Create a pane
BorderPane pane = new BorderPane();
pane.setTop(paneForControls);
pane.setCenter(textArea);
// Create and register handler
btShowTable.setOnAction(e -> {
print();
});
// Create a scene and place it in the stage
Scene scene = new Scene(pane);
primaryStage.setTitle("loans"); // Set the stage title
primaryStage.setScene(scene); // Place the scene in the stage
primaryStage.show(); // Display the stage
}
private void print() {
// Create a output string
String output = "";
double monthlyInterestRate; // Monthly interest rate
double monthlyPayment; // Monthly payment
// Add table header
output += "Interest Rate Monthly Payment Total Payment\n";
// Calculate and add table with interest rates to output
for (double i = 5.0; i <= 8; i += 0.125) {
monthlyInterestRate = i / 1200;
monthlyPayment = Double.parseDouble(tfLoanAmount.getText()) *
monthlyInterestRate / (1 - 1 / Math.pow(1 + monthlyInterestRate,
Double.parseDouble(tfNumberOfYears.getText()) * 12));
output += String.format("%-24.3f%-34.2f%-8.2f\n", i,
monthlyPayment, (monthlyPayment * 12) *
Double.parseDouble(tfNumberOfYears.getText()));
}
textArea.setText(output);
}
public static void main(String[] args) {
launch(args);
}
}
【问题讨论】:
-
您之前已经尝试过什么?异常处理需要在您的代码中的什么位置进行?将所有代码转储到 SO 上不会为您提供很多答案。
-
天哪。这是你可以很容易地用谷歌搜索的东西,这就是(被其他人)否决票的原因。他们不是刻薄,只是试图限制混乱。 if (!(isNumerc(tfLoanAmount.getText()))) {throw new IllegalArgumentException();} public static boolean isNumeric(String str) { return str.matches("-?\\d+(.\\d+)?" ); }
标签: java exception exception-handling