【问题标题】:java - exception handingjava - 异常处理
【发布时间】: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


【解决方案1】:

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 - 如果字符串为空

NumberFormatException - 如果字符串不包含可解析的双精度。

因此,您可以将该代码放在 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); 
}`

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

【讨论】:

    【解决方案2】:

    可能有很多方法可以解决这个问题,我能想到的一些方法是 if 语句,如果你知道会出现什么样的错误,正则表达式匹配只过滤有效输入,或者 try/catch,例如

    // 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);
    }
    

    【讨论】:

      猜你喜欢
      • 2013-09-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-06-03
      • 2020-12-09
      • 1970-01-01
      相关资源
      最近更新 更多