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

Hello, I am using IntelliJ IDEA with JavaFX to build a travel expensive calculator, but I...
Hello, I am using IntelliJ IDEA with JavaFX to build a travel expensive calculator, but I dont konw how to conver user input to doulbe. Pleasse teach me how to add all textfield and display it after I click submit. public class Main extends Application { @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...
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?
I am running this code using C to count the words in char array, but somehow...
I am running this code using C to count the words in char array, but somehow it keeps counting the total characters + 1. Any solution to fix this problem? #include <stdio.h> int main() {    char input[1001];    int count =0;    fgets(input, 1001, stdin);    char *array = input;    while(*array != '\0')       {        if(*array == ' '){            array++;        }        else{        count++;        array++;...
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).
I am having trouble fixing my build errors. The compiler I am using is Visual Studio.Thanks....
I am having trouble fixing my build errors. The compiler I am using is Visual Studio.Thanks. #include <iostream> #include <string> #include <cstdlib> using namespace std; /* * structure to store employee details * employee details are stored as linked list */ struct Employee { private:    string full_name; //full name    double net_income; //income public:    struct Employee *next; //pointing to the next employee details in the list                        /*                   ...
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
Build an interactive calculator. Using an Arduino Uno, the OLED Display and matrix keypad to build...
Build an interactive calculator. Using an Arduino Uno, the OLED Display and matrix keypad to build a simple calculator application. The user presses the operands and operators using the keypad. The calculation output should be displayed on the OLED display. You may make the following simplifying assumptions. a)Assume 1 digit numbers b) Assume only two operators ‘+’ and ‘-’ Upload the breadboard diagram and the code
.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
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT