Question

please help me debug this Create a Future Value Calculator that displays error messages in labels.GUISpecificationsStart...

please help me debug this

Create a Future Value Calculator that displays error messages in labels.GUISpecificationsStart with the JavaFX version of the Future Value application presented in chapter 17. Create error message labels for each text field that accepts user input. Use the Validation class from chapter 17 to validate user input.Format the application so that the controls don’t change position when error messages are displayed.

package murach.business;

public class Calculation {
  
    public static final int MONTHS_IN_YEAR = 12;

    public static double futureValue(double monthlyPayment,
            double yearlyInterestRate, int years) {
      
        int months = years * MONTHS_IN_YEAR;
        double monthlyInterestRate = yearlyInterestRate / MONTHS_IN_YEAR / 100;
        double futureValue = 0;
        for (int i = 1; i <= months;) {
            futureValue = (futureValue + monthlyPayment)
                    * (1 + monthlyInterestRate);
        }
        return futureValue;
    }
}

/***********************************************************************************

package murach.business;

public class Validation {
    private String lineEnd;
  
    public Validation() {
        this.lineEnd = "\n";
    }
    public Validation(String lineEnd) {
        this.lineEnd = lineEnd;
    }
  
    public String isPresent(String value, String name) {
        String msg = "";
        if (value.isEmpty()) {
            msg = name + " is required." + lineEnd;
        }
        return msg;
    }
  
    public String isDouble(String value, String name) {
        String msg = "";
         {
            Double.parseDouble(value);
        } catch (NumberFormatException e) {
            msg = name + " must be a valid number." + lineEnd;
        }
        return msg;
    }
  
    public String isInteger(String value, String name) {
        String msg = "";
        try {
            Integer.parseInt(value);
        } catch (NumberFormatException e) {
            msg = name + " must be an integer." + lineEnd;
        }
        return msg;
    }
}
/**************************************************************************************************************

package murach.ui;

import murach.business.Validation;
import murach.business.Calculation;
import java.text.NumberFormat;

import javafx.application.Application;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.control.TextField;
import javafx.scene.layout.GridPane;
import javafx.scene.layout.HBox;
import javafx.stage.Stage;

public class FutureValueApp extends Application {
    private TextField investmentField;
    private TextField interestRateField;
    private TextField yearsField;
    private TextField futureValueField;
  
    private Label investmentLabel;
    private Label interestRateLabel;
    private Label yearsLabel;
      
    @Override
    public void start(Stage primaryStage) {
        primaryStage.setTitle("Future Value Calculator");
      
        GridPane grid = new GridPane();
        grid.setAlignment(Pos.TOP_LEFT);
        grid.setPadding(new Insets(25, 25, 25, 25));
        grid.setHgap(10);
        grid.setVgap(10);

        Scene scene = new Scene(grid, 580, 220);
      
        grid.add(new Label("Monthly Investment:"), 0, 0);
        investmentField = new TextField();
        grid.add(investmentField, 1, 0);
        investmentLabel = new Label();
        grid.add(investmentLabel, 2, 0);

        grid.add(new Label("Yearly Interest Rate:"), 0, 1);
        interestRateField = new TextField();
        grid.add(interestRateField, 1, 1);
        interestRateLabel = new Label();
        grid.add(interestRateLabel, 2, 1);
      
        grid(new Label("Years:"), 0, 2);
        yearsField = new TextField();
        grid.add(yearsField, 1, 2);
        yearsLabel = new Label();
        grid.add(yearsLabel, 2, 2);
      
        grid.add(new Label("Future Value:"), 0, 3);
        futureValueField = new TextField();
        futureValueField.setEditable(false);
        grid.add(futureValueField, 1, 3);

        calculateButton = new Button("Calculate");
        calculateButton.setOnAction(event -> calculateButtonClicked());
      
        Button exitButton = new Button("Exit");
        exitButton.setOnAction(event -> exitButtonClicked());
      
        HBox buttonBox = new HBox(10);
        buttonBox.getChildren().add(calculateButton);
        buttonBox.getChildren().add(exitButton);
        buttonBox.setAlignment(Pos.BOTTOM_RIGHT);
        grid.add(buttonBox, 0, 4, 2, 1);
             
        primaryStage.setScene();
        primaryStage.show();
    }
  
    private void calculateButtonClicked() {
        // set error messages in labels
        Validation v = new Validation();
        investmentLabel.setText(
            v.isDouble(investmentField.getText(), "Monthly Investment") );      
        interestRateLabel.setText(
            v.isDouble(interestRateField.getText(), "Yearly Interest Rate") );      
        yearsLabel.setText( v.isDouble(yearsField.getText(), "Years") );
      
        // check if all error labels are empty
        if (investmentLabel.getText().isEmpty() &&
            interestRateLabel.getText().isEmpty() &&
            yearsLabel.getText().isEmpty()) {

            // get data from text fields
            double investment = Double.parseDouble(investmentField.getText());
            double rate = Double.parseDouble(interestRateField.getText());
            int years = Integer.parseInt(yearsField.getText());

            // calculate future value
            double futureValue = Calculation.futureValue(investment, rate, years);

            // set data in read-only text field
            NumberFormat currency = NumberFormat.getCurrencyInstance();
            futureValueField.setText(currency.format(futureValue));
        }      
    }

    private void exitButtonClicked() {
        System.exit(0);   // 0 indicates a normal exit
    }
  
    public static void main(String[] args) {
        launch(args);
    }     
}

0 0
Add a comment Improve this question Transcribed image text
Answer #1

Below is the solution:

There was some error in code its corrected.

import java.text.NumberFormat;

import javafx.application.Application;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.control.TextField;
import javafx.scene.layout.GridPane;
import javafx.scene.layout.HBox;
import javafx.stage.Stage;

public class FutureValueApp extends Application {
   private TextField investmentField;
   private TextField interestRateField;
   private TextField yearsField;
   private TextField futureValueField;

   private Label investmentLabel;
   private Label interestRateLabel;
   private Label yearsLabel;

   @Override
   public void start(Stage primaryStage) {
       primaryStage.setTitle("Future Value Calculator");

       GridPane grid = new GridPane();
       grid.setAlignment(Pos.TOP_LEFT);
       grid.setPadding(new Insets(25, 25, 25, 25));
       grid.setHgap(10);
       grid.setVgap(10);

       Scene scene = new Scene(grid, 580, 220);

       grid.add(new Label("Monthly Investment:"), 0, 0);
       investmentField = new TextField();
       grid.add(investmentField, 1, 0);
       investmentLabel = new Label();
       grid.add(investmentLabel, 2, 0);

       grid.add(new Label("Yearly Interest Rate:"), 0, 1);
       interestRateField = new TextField();
       grid.add(interestRateField, 1, 1);
       interestRateLabel = new Label();
       grid.add(interestRateLabel, 2, 1);

       grid.add(new Label("Years:"), 0, 2);
       yearsField = new TextField();
       grid.add(yearsField, 1, 2);
       yearsLabel = new Label();
       grid.add(yearsLabel, 2, 2);

       grid.add(new Label("Future Value:"), 0, 3);
       futureValueField = new TextField();
       futureValueField.setEditable(false);
       grid.add(futureValueField, 1, 3);

       Button calculateButton = new Button("Calculate");
       calculateButton.setOnAction(event -> calculateButtonClicked());

       Button exitButton = new Button("Exit");
       exitButton.setOnAction(event -> exitButtonClicked());

       HBox buttonBox = new HBox(10);
       buttonBox.getChildren().add(calculateButton);
       buttonBox.getChildren().add(exitButton);
       buttonBox.setAlignment(Pos.BOTTOM_RIGHT);
       grid.add(buttonBox, 0, 4, 2, 1);

       primaryStage.setScene(scene);
       primaryStage.show();
   }

   private void calculateButtonClicked() {
       //set the label to empty
       investmentLabel.setText("");
       interestRateLabel.setText("");
       yearsLabel.setText("");
       //// set error messages in labels
       Validation v = new Validation();
       investmentLabel.setText(v.isDouble(investmentField.getText(), "Monthly Investment"));
       interestRateLabel.setText(v.isDouble(interestRateField.getText(), "Yearly Interest Rate"));
       yearsLabel.setText(v.isInteger(yearsField.getText(), "Years"));
       //check if all error labels are empty
       if (investmentLabel.getText().isEmpty() && interestRateLabel.getText().isEmpty() && yearsLabel.getText().isEmpty()) {
           // get data from text fields
           double investment = Double.parseDouble(investmentField.getText());
           double rate = Double.parseDouble(interestRateField.getText());
           int years = Integer.parseInt(yearsField.getText());

           // calculate future value
           double futureValue = Calculation.futureValue(investment, rate, years);

           // set data in read-only text field
           NumberFormat currency = NumberFormat.getCurrencyInstance();
           futureValueField.setText(currency.format(futureValue));
       }
   }

   private void exitButtonClicked() {
       System.exit(0); // 0 indicates a normal exit
   }

   public static void main(String[] args) {
       launch(args);
   }
}

public class Calculation {
   public static final int MONTHS_IN_YEAR = 12;

   public static double futureValue(double monthlyPayment, double yearlyInterestRate, int years) {
       int months = years * MONTHS_IN_YEAR;
       double monthlyInterestRate = yearlyInterestRate / MONTHS_IN_YEAR / 100;
       double futureValue = 0;
       for (int i = 1; i <= months; i++) { //i increment was missing
           futureValue = (futureValue + monthlyPayment) * (1 + monthlyInterestRate); //calculate the future value by formula
       }
       return futureValue;
   }
}

public class Validation {
   private String lineEnd;

   public Validation() {
       this.lineEnd = "\n";
   }

   public Validation(String lineEnd) {
       this.lineEnd = lineEnd;
   }

   public String isPresent(String value, String name) {
       String msg = "";
       if (value.isEmpty()) {
           msg = name + " is required." + lineEnd;
       }
       return msg;
   }

   public String isDouble(String value, String name) {
       String msg = "";
       try {
           Double.parseDouble(value);
       } catch (NumberFormatException e) {
           msg = name + " must be a valid number." + lineEnd;
       }
       return msg;
   }

   public String isInteger(String value, String name) {
       String msg = "";
       try {
           Integer.parseInt(value);
       } catch (NumberFormatException e) {
           msg = name + " must be an integer." + lineEnd;
       }
       return msg;
   }
}

sample output:

Add a comment
Know the answer?
Add Answer to:
please help me debug this Create a Future Value Calculator that displays error messages in labels.GUISpecificationsStart...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
  • Add appropriate descriptive comments to each line of code in the project explaining why the code...

    Add appropriate descriptive comments to each line of code in the project explaining why the code is in the application. public class FutureValueFrame extends JFrame { private JTextField investmentField; private JTextField interestRateField; private JComboBox yearsComboBox; private JList futureValueList; private DefaultListModel futureValueModel; public FutureValueFrame() { initComponents(); } private void initComponents() { try { UIManager.setLookAndFeel( UIManager.getSystemLookAndFeelClassName()); } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException e) { System.out.println(e); } setTitle("Future Value Calculator"); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setLocationByPlatform(true); investmentField = new JTextField(); interestRateField = new JTextField();...

  • public static void main(String[] args) {         System.out.println("Welcome to the Future Value Calculator\n");         Scanner sc...

    public static void main(String[] args) {         System.out.println("Welcome to the Future Value Calculator\n");         Scanner sc = new Scanner(System.in);         String choice = "y";         while (choice.equalsIgnoreCase("y")) {             // get the input from the user             System.out.println("DATA ENTRY");             double monthlyInvestment = getDoubleWithinRange(sc,                     "Enter monthly investment: ", 0, 1000);             double interestRate = getDoubleWithinRange(sc,                     "Enter yearly interest rate: ", 0, 30);             int years = getIntWithinRange(sc,                     "Enter number of years: ", 0, 100);             System.out.println();            ...

  • Java: In this assignment, you will create an accumulator accumulator-calculator that displays a sad face “...

    Java: In this assignment, you will create an accumulator accumulator-calculator that displays a sad face “ :-( “ whenever the number displayed by the calculator is negative and a happy face “ :-) ” whenever the number displayed is positive. The calculator responds to the following commands: num + , num - , num * , num / and C ( Clear ). After initial run, if the user clicks 8 and then presses the “+” button for example, the...

  • use this code of converting Km to miles , to create Temperature converter by using java...

    use this code of converting Km to miles , to create Temperature converter by using java FX import javafx.application.Application; import javafx.stage.Stage; import javafx.scene.Scene; import javafx.scene.layout.HBox; import javafx.scene.layout.VBox; import javafx.geometry.Pos; import javafx.geometry.Insets; import javafx.scene.control.Label; import javafx.scene.control.TextField; import javafx.scene.control.Button; import javafx.event.EventHandler; import javafx.event.ActionEvent; /** * Kilometer Converter application */ public class KiloConverter extends Application { // Fields private TextField kiloTextField; private Label resultLabel; public static void main(String[] args) { // Launch the application. launch(args); } @Override public void start(Stage primaryStage) { //...

  • please help me debug this Create a GUI for an application that lets the user calculate...

    please help me debug this Create a GUI for an application that lets the user calculate the hypotenuse of a right triangle. Use the Pythagorean Theorem to calculate the length of the third side. The Pythagorean Theorem states that the square of the hypotenuse of a right-triangle is equal to the sum of the squares of the opposite sides: alidate the user input so that the user must enter a double value for side A and B of the triangle....

  • It's not showing anything. I've tried many things but only a small window pops up. Below...

    It's not showing anything. I've tried many things but only a small window pops up. Below is my code so far. It's creating a Mortgage Calculator with GUI. Having user input the principle, term, and rate. ************************************************************************************************************************** import java.awt.*; import java.awt.event.*; import javax.swing.*; public class Mortgage extends JFrame implements ActionListener { //declaring components private JTextField principle, rate, terms, result; private JButton calculate, reset, exit;       //constructor    public Mortgage() { setLayout(new GridLayout(0,2)); //adding labels and textfields add(new JLabel("Principle:")); principle...

  • Need help debugging Create a GUI application that accepts student registration data. Specifications: The text box...

    Need help debugging Create a GUI application that accepts student registration data. Specifications: The text box that displays the temporary password should be read-only. The temporary password consists of the user’s first name, an asterisk (*), and the user’s birth year. If the user enters data in the first three fields, display a temporary password in the appropriate text field and a welcome message in the label below the text fields. If the user does not enter data, clear the...

  • In this practice program you are going to practice creating graphical user interface controls and placing...

    In this practice program you are going to practice creating graphical user interface controls and placing them on a form. You are given a working NetBeans project shell to start that works with a given Invoice object that keeps track of a product name, quantity of the product to be ordered and the cost of each item. You will then create the necessary controls to extract the user input and display the results of the invoice. If you have any...

  • Can someone modify my code so that I do not get this error: Exception in thread...

    Can someone modify my code so that I do not get this error: Exception in thread "main" java.lang.NullPointerException at java.awt.Container.addImpl(Container.java:1043) at java.awt.Container.add(Container.java:363) at RatePanel.<init>(RatePanel.java:64) at CurrencyConverter.main(CurrencyConverter.java:16) This code should get the amount of money in US dollars from user and then let them select which currency they are trying to convert to and then in the textfield print the amount //********************************************************************* //File name: RatePanel.java //Name: Brittany Hines //Purpose: Panel for a program that convers different currencyNamerencies to use dollars //*********************************************************************...

  • Can someone help me to figure that error I have put below. JAVA ----jGRASP exec: javac...

    Can someone help me to figure that error I have put below. JAVA ----jGRASP exec: javac -g P4Program.java P4Program.java:94: error: package list does not exist Iterator i = new list.iterator(); ^ 1 error ----jGRASP wedge2: exit code for process is 1. ----jGRASP: operation complete. Note: Below there are two different classes that work together. Each class has it's own fuctions/methods. import java.util.*; import java.io.*; public class P4Program{ public void linkedStackFromFile(){ String content = new String(); int count = 1; File...

ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT