Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Help with try-catch blocks. I just can\'t seem to get them to work right. Help!

ID: 3794640 • Letter: H

Question

Help with try-catch blocks. I just can't seem to get them to work right. Help!

import java.text.DecimalFormat;
import javafx.scene.layout.AnchorPane;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.HBox;
import javafx.scene.layout.StackPane;
import javafx.scene.text.Text;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.scene.Scene;
import javafx.scene.text.*;
import javafx.scene.control.Alert;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.control.TextArea;
import javafx.scene.control.TextField;
import javafx.scene.image.ImageView;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.application.Application;
import javafx.stage.Stage;
import javafx.stage.WindowEvent;
import javafx.application.Platform;

public class LoanComparison extends Application
{
    public static void main(String[] args) {
        launch(args);
    }
    // Creating and naming private variables for text fields(user input).
    private TextField LoanAmount = new TextField();
    private TextField NumberOfYears = new TextField();
    private TextArea ResultsTable = new TextArea();
    //Creating button that when pressed displays the results table.
    private Button ShowTable = new Button("Show Table");

    @Override
    public void start(Stage primaryStage)
    {
        //Creating new Border Pane
        final BorderPane pane = new BorderPane();
        //Creating HBox for user interface
        HBox Interface = new HBox(12);
        //Creating labels for text fields
        Label LoanAmt = new Label("Loan Amount: ");
        Label NumYears = new Label("Years: ");
        //Setting width of text fields
        LoanAmount.setPrefWidth(150);
        NumberOfYears.setPrefWidth(35);
        //Centering interface
        Interface.setAlignment(Pos.CENTER);
        //Adding TextFields, Labels and Button to Interface.
        Interface.getChildren().addAll(LoanAmt, LoanAmount, NumberOfYears, NumYears, ShowTable);
        //Adding Interface to the top of pane and ResultsTable to the center.
        pane.setTop(Interface);
        pane.setCenter(ResultsTable);

        //Setting margins and padding for
        BorderPane.setMargin(ResultsTable, new Insets(5, 1, 1, 1));
        pane.setPadding(new Insets(5, 5, 5, 5));
        //Method that caculates and outputs the results when the user presses the "Show Table" button
        ShowTable.setOnAction(e -> Calculate());
        //Setting the size the pane
        Scene scene = new Scene(pane,500, 500);
        //Naming the pane
        primaryStage.setTitle("Loan Comparison");
        primaryStage.setScene(scene);
        primaryStage.show();
        ResultsTable.setEditable(false);
    }

    private void Calculate()
    {

        //Declaring/Defining variables for calculations and try catch blocks.
        boolean ValidInput = true;
        Loan Lloan = new Loan ();
        //Try Catch block for catches vales less than 1000 or greater than 100000.
        try
        {

            Lloan.setAnnualInterestRate(5);
            Lloan.setLoanAmount(Double.parseDouble(LoanAmount.getText()));
            if (Lloan.getLoanAmount() < 1000 || Lloan.getLoanAmount() > 100000)
            {
                throw new Exception();

            }
        }
        catch(Exception e){
            new Alert(Alert.AlertType.ERROR,("Invalid Input: Only loan amounts from 1000 to 100000 will be accepted.")).showAndWait();
            ValidInput = false;

        }

        try{
            Double LoanYears = 0.0;
            Lloan.setNumberOfYears(Integer.parseInt(NumberOfYears.getText()));
            if(LoanYears < 1 || LoanYears > 20)
            {
                throw new Exception();

            }
        }
        catch(Exception f)
        {
            new Alert(Alert.AlertType.ERROR,("Invalid Input: The number of years must be from 1 to 20.")).showAndWait();
            ValidInput = false;

        }
        if (ValidInput = true)
        {
            //Adding column names to table.
            ResultsTable.setText("Interest Rate                    Monthly Payment                    "
                + "Total Payment ");
            //Do While loop for calculating/printing values until the interest rate reaches 8%
            do
            {

                ResultsTable.appendText(new DecimalFormat("0.000%").format(Lloan.getAnnualInterestRate()/100.0) + "                                    " +
                    new DecimalFormat("$###,##0.00").format(Lloan.getMonthlyPayment()) + "                            " +
                    new DecimalFormat("$###,##0.00").format(Lloan.getTotalPayment()) + " ");
                Lloan.setAnnualInterestRate(Lloan.getAnnualInterestRate() + 0.125);

            } while (Lloan.getAnnualInterestRate() <= 8);
        }

     

    }
}

public class Loan {
private double annualInterestRate;
private int numberOfYears;
private double loanAmount;
private java.util.Date loanDate;

/** Default constructor */
public Loan() {
    this(2.5, 1, 1000);
}

/** Construct a loan with specified annual interest rate,
      number of years, and loan amount
    */
public Loan(double annualInterestRate, int numberOfYears,
      double loanAmount) {
    this.annualInterestRate = annualInterestRate;
    this.numberOfYears = numberOfYears;
    this.loanAmount = loanAmount;
    loanDate = new java.util.Date();
}

/** Return annualInterestRate */
public double getAnnualInterestRate() {
    return annualInterestRate;
}

/** Set a new annualInterestRate */
public void setAnnualInterestRate(double annualInterestRate) {
    this.annualInterestRate = annualInterestRate;
}

/** Return numberOfYears */
public int getNumberOfYears() {
    return numberOfYears;
}

/** Set a new numberOfYears */
public void setNumberOfYears(int numberOfYears) {
    this.numberOfYears = numberOfYears;
}

/** Return loanAmount */
public double getLoanAmount() {
    return loanAmount;
}

/** Set a newloanAmount */
public void setLoanAmount(double loanAmount) {
    this.loanAmount = loanAmount;
}

/** Find monthly payment */
public double getMonthlyPayment() {
    double monthlyInterestRate = annualInterestRate / 1200;
    double monthlyPayment = loanAmount * monthlyInterestRate / (1 -
      (1 / Math.pow(1 + monthlyInterestRate, numberOfYears * 12)));
    return monthlyPayment;  
}

/** Find total payment */
public double getTotalPayment() {
    double totalPayment = getMonthlyPayment() * numberOfYears * 12;
    return totalPayment;  
}

/** Return loan date */
public java.util.Date getLoanDate() {
    return loanDate;
}

Explanation / Answer

There are two bugs in your code, which is the reason why you are seeing the odd-behavior of displaying the table even when the loan-amount and loan-year is out of defined range. And moreover, you are seeing the alert dialog all the time even if the loan-year value is within the range. Let's go through the bugs one-by-one.

        try{
            Double LoanYears = 0.0;
            Lloan.setNumberOfYears(Integer.parseInt(NumberOfYears.getText()));
            if(LoanYears < 1 || LoanYears > 20)
            {
                throw new Exception();

            }
        }
        catch(Exception f)
        {
          ...      

}

In the above code, LoanYears variable is being set to 0 all the time. You are not assigning it to actual input value from the user. Therefore when the expression if(LoanYears < 1 || LoanYears > 20), will always evaluate to true and the exception is thrown, which results in displaying the alert box every time.
Instead replace the above code with the following piece of code. I have highlighted the changes made in bold font.

        try {
           Integer LoanYears = 0;
           Lloan.setNumberOfYears(Integer.parseInt(NumberOfYears.getText()));
           LoanYears = Lloan.getNumberOfYears();
            if (LoanYears < 1 || LoanYears > 20) {
               throw new Exception();

           }
       } catch (Exception f) {
           new Alert(Alert.AlertType.ERROR, ("Invalid Input: The number of years must be from 1 to 20."))
                   .showAndWait();
           ValidInput = false;
        }


Now let us consider the second issue where the table is displayed even when the values of out of range. This is because in the final if condition you are using = instead of == to check whether the condition is true. Using '=' will assign validInput to true and the condition evaluates to true all the time. Hence the odd behavior.

if (ValidInput = true)
{
         //Adding column names to table.
         ResultsTable.setText("Interest Rate                    Monthly Payment                    "
                + "Total Payment ");

....
....
....

}

Replace the above if-condition with the below one

if (ValidInput == true)
{
        ....
....
....

}

Below is the entire piece of corrected code

import javafx.application.Application;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.layout.StackPane;
import javafx.stage.Stage;

import java.text.DecimalFormat;
import javafx.scene.layout.AnchorPane;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.HBox;
import javafx.scene.layout.StackPane;
import javafx.scene.text.Text;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.scene.Scene;
import javafx.scene.text.*;
import javafx.scene.control.Alert;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.control.TextArea;
import javafx.scene.control.TextField;
import javafx.scene.image.ImageView;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.application.Application;
import javafx.stage.Stage;
import javafx.stage.WindowEvent;
import javafx.application.Platform;

public class LoanComparison extends Application {
   public static void main(String[] args) {
       launch(args);
   }

   // Creating and naming private variables for text fields(user input).
   private TextField LoanAmount = new TextField();
   private TextField NumberOfYears = new TextField();
   private TextArea ResultsTable = new TextArea();
   // Creating button that when pressed displays the results table.
   private Button ShowTable = new Button("Show Table");

   @Override
   public void start(Stage primaryStage) {
       // Creating new Border Pane
       final BorderPane pane = new BorderPane();
       // Creating HBox for user interface
       HBox Interface = new HBox(12);
       // Creating labels for text fields
       Label LoanAmt = new Label("Loan Amount: ");
       Label NumYears = new Label("Years: ");
       // Setting width of text fields
       LoanAmount.setPrefWidth(150);
       NumberOfYears.setPrefWidth(35);
       // Centering interface
       Interface.setAlignment(Pos.CENTER);
       // Adding TextFields, Labels and Button to Interface.
       Interface.getChildren().addAll(LoanAmt, LoanAmount, NumberOfYears, NumYears, ShowTable);
       // Adding Interface to the top of pane and ResultsTable to the center.
       pane.setTop(Interface);
       pane.setCenter(ResultsTable);

       // Setting margins and padding for
       BorderPane.setMargin(ResultsTable, new Insets(5, 1, 1, 1));
       pane.setPadding(new Insets(5, 5, 5, 5));
       // Method that caculates and outputs the results when the user presses
       // the "Show Table" button
       ShowTable.setOnAction(e -> Calculate());
       // Setting the size the pane
       Scene scene = new Scene(pane, 500, 500);
       // Naming the pane
       primaryStage.setTitle("Loan Comparison");
       primaryStage.setScene(scene);
       primaryStage.show();
       ResultsTable.setEditable(false);
   }

   private void Calculate() {

       // Declaring/Defining variables for calculations and try catch blocks.
       boolean ValidInput = true;
       Loan Lloan = new Loan();
       // Try Catch block for catches vales less than 1000 or greater than
       // 100000.
       try {

           Lloan.setAnnualInterestRate(5);
           Lloan.setLoanAmount(Double.parseDouble(LoanAmount.getText()));
           if (Lloan.getLoanAmount() < 1000 || Lloan.getLoanAmount() > 100000) {
               throw new Exception();

           }
       } catch (Exception e) {
           new Alert(Alert.AlertType.ERROR, ("Invalid Input: Only loan amounts from 1000 to 100000 will be accepted."))
                   .showAndWait();
           ValidInput = false;

       }

       try {
           Integer LoanYears = 0;
           Lloan.setNumberOfYears(Integer.parseInt(NumberOfYears.getText()));
           LoanYears = Lloan.getNumberOfYears();
                        if (LoanYears < 1 || LoanYears > 20) {
               throw new Exception();

           }
       } catch (Exception f) {
           new Alert(Alert.AlertType.ERROR, ("Invalid Input: The number of years must be from 1 to 20."))
                   .showAndWait();
           ValidInput = false;

       }
       if (ValidInput == true) {
           // Adding column names to table.
           ResultsTable.setText(
                   "Interest Rate                    Monthly Payment                    " + "Total Payment ");
           // Do While loop for calculating/printing values until the interest
           // rate reaches 8%
           do {

               ResultsTable.appendText(new DecimalFormat("0.000%").format(Lloan.getAnnualInterestRate() / 100.0)
                       + "                                    "
                       + new DecimalFormat("$###,##0.00").format(Lloan.getMonthlyPayment())
                       + "                            "
                       + new DecimalFormat("$###,##0.00").format(Lloan.getTotalPayment()) + " ");
               Lloan.setAnnualInterestRate(Lloan.getAnnualInterestRate() + 0.125);

           } while (Lloan.getAnnualInterestRate() <= 8);
       }

   }
}

public class Loan {
   private double annualInterestRate;
   private int numberOfYears;
   private double loanAmount;
   private java.util.Date loanDate;

   /** Default constructor */
   public Loan() {
       this(2.5, 1, 1000);
   }

   /**
   * Construct a loan with specified annual interest rate, number of years,
   * and loan amount
   */
   public Loan(double annualInterestRate, int numberOfYears, double loanAmount) {
       this.annualInterestRate = annualInterestRate;
       this.numberOfYears = numberOfYears;
       this.loanAmount = loanAmount;
       loanDate = new java.util.Date();
   }

   /** Return annualInterestRate */
   public double getAnnualInterestRate() {
       return annualInterestRate;
   }

   /** Set a new annualInterestRate */
   public void setAnnualInterestRate(double annualInterestRate) {
       this.annualInterestRate = annualInterestRate;
   }

   /** Return numberOfYears */
   public int getNumberOfYears() {
       return numberOfYears;
   }

   /** Set a new numberOfYears */
   public void setNumberOfYears(int numberOfYears) {
       this.numberOfYears = numberOfYears;
   }

   /** Return loanAmount */
   public double getLoanAmount() {
       return loanAmount;
   }

   /** Set a newloanAmount */
   public void setLoanAmount(double loanAmount) {
       this.loanAmount = loanAmount;
   }

   /** Find monthly payment */
   public double getMonthlyPayment() {
       double monthlyInterestRate = annualInterestRate / 1200;
       double monthlyPayment = loanAmount * monthlyInterestRate
               / (1 - (1 / Math.pow(1 + monthlyInterestRate, numberOfYears * 12)));
       return monthlyPayment;
   }

   /** Find total payment */
   public double getTotalPayment() {
       double totalPayment = getMonthlyPayment() * numberOfYears * 12;
       return totalPayment;
   }

   /** Return loan date */
   public java.util.Date getLoanDate() {
       return loanDate;
   }
}

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote