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
  • 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) { //...

  • 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...

  • 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....

  • Use Kilometer Converter application code to write Temperature Converter application to convert degrees Fahrenheit into degrees...

    Use Kilometer Converter application code to write Temperature Converter application to convert degrees Fahrenheit into degrees Celsius ((F - 32)*5/9). It needs to be JavaFX 1 import javafx.application. Application; 2 import javafx.stage. Stage; 3 import javafx.scene. Scene; 4 import javafx.scene.layout.HBox; 5 import javafx.scene.layout. VBox; 6 import javafx.geometry.Pos; 7 import javafx.geometry.Insets; 8 import javafx.scene.control.Label; 9 import javafx.scene.control. TextField; 10 import javafx.scene.control.Button; 11 import javafx.event. EventHandler; 12 import javafx.event. ActionEvent; 13 14 ** 15 * Kilometer Converter application 16 17 18 public...

  • / Finish the code to make it work import static javafx.application.Application.launch; import java.io.File; import javafx.application.Application; import...

    / Finish the code to make it work import static javafx.application.Application.launch; import java.io.File; import javafx.application.Application; import javafx.event.ActionEvent; import javafx.geometry.Insets; import javafx.geometry.Pos; import javafx.scene.Scene; import javafx.scene.control.Button; import javafx.scene.control.ChoiceBox; import javafx.scene.control.Label; import javafx.scene.layout.HBox; import javafx.scene.layout.VBox; import javafx.scene.media.AudioClip; import javafx.stage.Stage; public class JukeBox extends Application { private ChoiceBox<String> choice; private AudioClip[] tunes; private AudioClip current; private Button playButton, stopButton;    //----------------------- // presents an interface that allows the user to select and play // a tune from a drop down box //-----------------------   ...

  • 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 //*********************************************************************...

  • This is my code. I need the UML for this code My code: public class Main...

    This is my code. I need the UML for this code My code: public class Main extends FlightManager {    Stage window;    Scene scene;    Button button;    HBox layout = new HBox(20);    Label dateTxt, airlineTxt, originTxt, destTxt, clssTxt, scopeTxt, adultsTxt, childTxt;    @Override public void start(Stage stage) { // create the UI and show it here    window = stage; window.setTitle("Reservations 2020"); button = new Button("New Flight");    VBox group3 = new VBox(10); dateTxt = Text("", group3);...

  • 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
ADVERTISEMENT