java - 异常处理

时间:2016-04-19 22:21:19

标签: java exception exception-handling

我创建了这个程序,让用户在文本字段中输入年数的贷款金额和贷款期限,并显示每个利率的月付款和总付款从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); 
    }
}

2 个答案:

答案 0 :(得分:0)

TextField(tfNumberOfYears)[TextField]:https://docs.oracle.com/javase/8/javafx/api/javafx/scene/control/TextField.html, 此TextField有一个方法public final String getText(),此方法返回一个String。

使用[Double.parseDouble(tfNumberOfYears.getText())]时:https://docs.oracle.com/javase/7/docs/api/java/lang/Double.html

public static double parseDouble(String s) throws NumberFormatException

抛出:

NullPointerException - 如果字符串为null

NumberFormatException - 如果字符串不包含可解析的double。

因此,您可以将该代码放入try / catch块中,并在用户输入5而不是5时生成您想要的内容。

像:

`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;
        try{
            monthlyPayment = Double.parseDouble(tfLoanAmount.getText()) * 
            monthlyInterestRate / (1 - 1 / Math.pow(1 + monthlyInterestRate,
            Double.parseDouble(tfNumberOfYears.getText()) * 12));
        }
        catch(NumberFormatException e){
            //Here you write the code to manage this exception

        }
        try{
            output += String.format("%-24.3f%-34.2f%-8.2f\n", i, 
            monthlyPayment, (monthlyPayment * 12) * 
            Double.parseDouble(tfNumberOfYears.getText()));
        }
        catch(NumberFormatException e){
            //Here you write the code to manage this exception

        }
    }

    textArea.setText(output);
}
    public static void main(String[] args) {
        launch(args); 
}`

这只是如何处理该异常的一个例子。

答案 1 :(得分:0)

可能有很多方法可以解决这个问题,有些我能想到的就是if语句,如果你知道期望什么类型的错误,正则表达式匹配只过滤有效输入,或尝试/捕获,例如

// if the userinput string matches a number
if( userInputNumber.matches("-?\\d+(\\.\\d+)?") ) {
    // put your code here
else {
    System.out.println("Input unrecognized. Please type in a number (e.g. "5")
}

或者

try {
    double userInputNumber = Double.parseDouble(loan.getText());
    // do some code
catch (Exception ex) {
    System.out.println("Error, unrecognized input.");
    System.out.println(ex);
}