Question

In: Computer Science

I am using IntelliJ IDEA with JavaFX to build a travel expensive calculator, but somehow it...

I am using IntelliJ IDEA with JavaFX to build a travel expensive calculator, but somehow it 

wouldn't calculate total expensive? It was working until I add the TextFieldListener because I need to make sure user

only input either mile driven or airfareCost. Please help me figure out what I did wrong.

import javafx.application.Application;
import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import javafx.event.EventHandler;
import javafx.fxml.FXMLLoader;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.scene.Parent;
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 Main extends Application {

    TextField field1, field2, field3, field4, field5, field6;
    Button submitButton, cancelButton;

    @Override
    public void start(Stage primaryStage) throws Exception{

        Label label1 = new Label ("(1) Number of days on the trip");
        Label label2 = new Label ("(2) Transportation cost (choose one only)");
        Label label3 = new Label ("Airfare Cost ");
        Label label4 = new Label ("Miles driven  ");
        Label label5 = new Label ("(3) Conference registration cost ");
        Label label6 = new Label ("(4) Lodging Cost (per night) ");
        Label label7 = new Label ("(5) Food cost (total) ");
        Label TotalExpensive = new Label("Total expenses: ");
        Label TotalExpensiveResult = new Label(" ");
        Label TotalCost = new Label("How much you own: ");
        Label TotalCostResult = new Label(" ");

        field1 = new TextField();
        field2 = new TextField();
        field3 = new TextField();
        field4 = new TextField();
        field5 = new TextField();
        field6 = new TextField();//all textfield

        submitButton = new Button ("Submit"); //Create submit button
        submitButton.setDisable( true);
        cancelButton = new Button ("Cancel"); //Create Cancel button


        HBox hBox = new HBox(20, label1, field1);
        HBox hBox1 = new HBox(10, label2);
        HBox hBox2 = new HBox(15, label3, field2);
        HBox hBox3 = new HBox(10, label4, field3);
        HBox hBox4 = new HBox(12, label5, field4);
        HBox hBox5 = new HBox(32, label6, field5);
        HBox hBox6 = new HBox(75, label7, field6);
        HBox hBox7 = new HBox(20, submitButton, cancelButton);
        HBox hBox8 = new HBox(20, TotalExpensive, TotalExpensiveResult);
        HBox hBox9 = new HBox(20, TotalCost, TotalCostResult);


        hBox.setAlignment(Pos.BASELINE_RIGHT); //Alignment
        hBox1.setAlignment(Pos.BASELINE_LEFT);
        hBox2.setAlignment(Pos.BASELINE_RIGHT);
        hBox3.setAlignment(Pos.BASELINE_RIGHT);
        hBox4.setAlignment(Pos.BASELINE_RIGHT);
        hBox5.setAlignment(Pos.BASELINE_RIGHT);
        hBox6.setAlignment(Pos.BASELINE_RIGHT);
        hBox7.setAlignment(Pos.CENTER);
        hBox8.setAlignment(Pos.BASELINE_LEFT);
        hBox9.setAlignment(Pos.BASELINE_LEFT);



        hBox1.setPadding(new Insets(0,0,15,0));
        hBox3.setPadding(new Insets(0,0,15,0));
        hBox7.setPadding(new Insets(15,0,0,0));
        hBox8.setPadding(new Insets(0,0,15,0));
        hBox9.setPadding(new Insets(0,0,15,0));

        TextFieldListener listener = new TextFieldListener();
        field1.textProperty().addListener(listener);
        field2.textProperty().addListener(listener);
        field3.textProperty().addListener(listener);
        field4.textProperty().addListener(listener);
        field5.textProperty().addListener(listener);
        field6.textProperty().addListener(listener);



        GridPane gridPane = new GridPane ();

        gridPane.add(hBox, 0, 0);
        gridPane.add(hBox1, 0, 1);
        gridPane.add(hBox2, 0, 2);
        gridPane.add(hBox3, 0, 3);
        gridPane.add(hBox4, 0, 4);
        gridPane.add(hBox5, 0, 5);
        gridPane.add(hBox6, 0, 6);
        gridPane.add(hBox7, 0, 7);
        gridPane.add(hBox8, 0, 8);
        gridPane.add(hBox9, 0, 9);
        gridPane.setAlignment(Pos.CENTER);
        gridPane.setPadding( new Insets(20, 20, 20, 20));
        gridPane.setVgap( 10);
        gridPane.setHgap( 10);
        primaryStage.setTitle("Travel Expenses Calculator");
        primaryStage.setScene(new Scene (gridPane));
        primaryStage.show();

        submitButton.setOnAction(event ->
        {

            double days = Double.parseDouble(field1.getText());
            double airFare = Double.parseDouble(field2.getText());
            double miles = Double.parseDouble(field3.getText());
            double ConregCost = Double.parseDouble(field4.getText());
            double lodgingCost = Double.parseDouble(field5.getText());
            double foodCost = Double.parseDouble(field6.getText());

            TotalExpensiveResult.setText(" " + ( airFare+ foodCost + ConregCost + (days * lodgingCost)) );

        });





    }

    private class TextFieldListener implements ChangeListener<String>
    {
        @Override
        public void changed(ObservableValue<? extends String> source, String oldValue, String
                newValue)
        {
            String numTrip = field1.getText();
            String airFare = field2.getText();
            String miles = field3.getText();
            String confCost = field4.getText();
            String lodgingCost = field5.getText();
            String foodCost = field6.getText();

            if (airFare.trim().equals( "")  )
            {
                submitButton.setDisable(numTrip.trim().equals( "") ||miles.trim().equals( "") || confCost.trim().equals( "")||
                        lodgingCost.trim().equals( "")|| foodCost.trim().equals( ""));
            }

            else if (miles.trim().equals( "") )
            {
                submitButton.setDisable(numTrip.trim().equals( "") ||airFare.trim().equals( "") || confCost.trim().equals( "")||
                        lodgingCost.trim().equals( "")|| foodCost.trim().equals( ""));
            }

            else
            {
                submitButton.setDisable( true);
            }


        }
    };




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

Solutions

Expert Solution

Either mile driven or air fare cost is going to remain empty, as per your requirement. But, on clicking the submit button, you are parsing both the fields. This is causing an parsing related exception while parsing one of the fields [Double.parseDouble()]. Checking for non-empty values before parsing will resolve the issue. Here is the modified setOnAction method. Also, found that the 'miles' variable is not used in the calculation.

submitButton.setOnAction(event ->
{

    double days = Double.parseDouble(field1.getText());
    String field2Str = field2.getText();
    double airFare = field2Str == null || field2Str.trim().isEmpty() ? 0 : Double.parseDouble(field2Str.trim());
    String field3Str = field3.getText();
    double miles = field3Str == null || field3Str.trim().isEmpty() ? 0 : Double.parseDouble(field3Str.trim());
    double ConregCost = Double.parseDouble(field4.getText());
    double lodgingCost = Double.parseDouble(field5.getText());
    double foodCost = Double.parseDouble(field6.getText());

    TotalExpensiveResult.setText(" " + ( airFare+ foodCost + ConregCost + (days * lodgingCost)) );

});

Please provide feedback for this answer.


Related Solutions

Using the BAII Plus calculator I am having a difficult time using this calculator to solve...
Using the BAII Plus calculator I am having a difficult time using this calculator to solve this MIRR 0 =-325,000 1=50,000 2= 75,000 3=-60,000 4=225,000 5=300,000 Required rate of return =15% We discount all negative CFs(at 15%) time 0 We compound all positive cash flows (at 15%) to 5 years This is now the TV or Terminal Value Please help me understand how to calculate these numbers?
Using the IntelliJ IDEA tool, write a program that will print a Christmas tree with the...
Using the IntelliJ IDEA tool, write a program that will print a Christmas tree with the "*". The tree should have at least 10 lines. Look back at the birthday cake lab for examples of how to do this lab. Submit a screen shot of your output in the console (i.e. non REPL tool).
how to prepare a proposal for your business idea? if i am taking a idea to...
how to prepare a proposal for your business idea? if i am taking a idea to open a restaurant entreprenurship
.Suppose I am in a boat and I travel at the bearing N70E at 30 knots...
.Suppose I am in a boat and I travel at the bearing N70E at 30 knots for 4 hours. Then, I turn 90 degrees clockwise and travel for 5 hours at the same speed. Find my bearing relative to the dock.
Hey, I have a code that I am working on to make a garden plot calculator,...
Hey, I have a code that I am working on to make a garden plot calculator, however I am reaching an error that I cannot seem to get past. Please help. import math # GarednPlot contains all the utility functions class GardenPlot: # constructor function: Welcomes the user and sets default values def __init__(self): print("Welcome!") self.length = 0 self.radius = 0 self.depth = 0 # Sets the length of the GardenPlot and returns that length def setLength(self): self.length = float(input("Enter...
I need the solution by Hand since I have no idea About Excel and am not...
I need the solution by Hand since I have no idea About Excel and am not allowed to use it on the exam. TIA 1. What is the beta of firm XXX over a 6 month period ? Could you please explain very thoroughly and step-by-step. I really struggle with the topic yet Average month market return: 1/1/1/-1/-1/-1 Average stock Price changes: 2/0/1/-1/0/-2
I am working on an Arduino Project. I would like to build a controllable RGB LED...
I am working on an Arduino Project. I would like to build a controllable RGB LED Nightlight (with a debounce code included). With each time pushing the button I want a different color. like the following Initial state = LED off first press= LED turns on Red second Press = LED turns on Green third Press = LED turns on Blue Fourth Press = LED turns on Purple Fifth Press = LED turns on Teal sixth press= LED turns on...
How would I complete this using a scientific calculator?
You invest $100 in a risky asset with an expected rate of return of 0.12 and a standard deviation of 0.15 and a T-bill with a rate of return of 0.05.What percentages of your money must be invested in the risky asset and the risk-free asset, respectively, to form a portfolio with an expected return of 0.09?How would I complete this using a scientific calculator?
I am a travel agent, I book in-city ride tickets and also ship your luggage to...
I am a travel agent, I book in-city ride tickets and also ship your luggage to the next destination. 1-NYC All Around Town it is $29.00 2-Big Bus NYC Tour it is $49.00 3-NYC one day guided Sightseeing Tour it is $89.00 4-Circle Line Complete Manhattan Island Cruise is $44.00 5-Viator VIP: Empire State Building, Statue of Liberty and 9/11 Memorial is $129.00 I also provide a quote for your shipment to be mailed to your next destination. In order...
I am looking for someone to build a spreadsheet in excel that can quickly answers these...
I am looking for someone to build a spreadsheet in excel that can quickly answers these type of questions by inputting the data. Thanks 1.Suppose that on Monday, 16 November, you assume a long position in one yen futures contract at the futures price of $0.0083. The initial margin is $4,590, and the maintenance margin is $3,400. The contract size is ¥12,500,000. For simplicity, you do not withdraw excess money from your margin balance. All margin requirements are met with...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT