-1

I'm hoping someone can help me with this InvocationTargetException I'm getting.

So here's the issue: I want to get a calculation done upon clicking the button btn. I couldn't assign the other variables perL, perG etc within the EventHandler or lambda expression, so I tried assigning them outside. Now when I click the button, I get the InvocationTargetException in my terminal. Can anyone offer any possibilities as to what's going wrong?

Here is the code:

package miniproject_v1;

import java.io.*;
import javafx.application.Application;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.scene.Scene;
import javafx.scene.control.*;
import javafx.scene.layout.VBox;
import javafx.scene.layout.HBox;
import javafx.stage.Stage;
import javafx.geometry.Insets;


public class MiniProject_v1 extends Application {

    @Override
    public void start(Stage primaryStage) {        

        double dieselCost = 0; 
        double octaneCost = 0;

        //try-catch block for file I/O
        try {
            File fuelCost = new File("fuelCost.csv"); //creating the fuel file object, and/or checking if it exists
            if (fuelCost.createNewFile()) {
                System.out.println("File created: " + fuelCost.getName());

            } else {
                System.out.println("File already exists.");
                BufferedReader csvReader = new BufferedReader(new FileReader(fuelCost)); //reading the fuel cost from the file
                                                                                         // the file itself is only 2 lines
                dieselCost = Double.parseDouble(csvReader.readLine());
                octaneCost = Double.parseDouble(csvReader.readLine());


                csvReader.close(); 
            }

        } catch (IOException e) {
            System.out.println("An error occurred.");
        }


        // printing fuel cost to check if they've been set properly
        System.out.println(dieselCost);
        System.out.println(octaneCost);


        TextField distance = new TextField(); //Text field for user input - distance
        Label distLab = new Label("Distance:"); // Label for text field
        distance.setPromptText("Enter distance in miles..."); //Text field prompt text


        TextField eff = new TextField(); //text field for user input - fuel efficiency 
        Label effLab = new Label("Efficiency:"); // label for fuel efficiency text field
        eff.setPromptText("Enter fuel efficiency in mpg...");// Text field prompt text


        //ObservableList used for the combobox options, next section
        ObservableList<String> fuels = 
            FXCollections.observableArrayList(
                "Diesel",
                "98 Octane"
            );


        // combo box for fuel choice, including label, options, padding and prompt text
        ComboBox fuelChoice = new ComboBox(); 
        Label fuelLabel = new Label("Fuel choice:");
        fuelChoice.getItems().addAll(fuels);
        fuelChoice.setPadding(new Insets(0, 0, 0, 120));
        fuelChoice.setPromptText("Select fuel");


        distLab.setPadding(new Insets(3));

        effLab.setPadding(new Insets(3));


        VBox textura = new VBox();
        textura.getChildren().addAll(distance, eff, fuelChoice);
        VBox.setMargin(fuelChoice,new Insets(30, 0, 0, 0));
        textura.setPadding(new Insets(0, 0, 0, 30));

        double perL = 0; //will be used to assist in the cost conversion from per-litre to per-gallon
        if(fuelChoice.getValue()=="Diesel"){
            perL = dieselCost;
        }else if (fuelChoice.getValue() == "98 Octane"){
            perL = octaneCost; 
        }
        double perG = perL * 3.785;
        double inputDistance = Double.parseDouble(distance.getText());
        double inputEff = Double.parseDouble(eff.getText());
        double requiredG = inputDistance/inputEff;


        Button btn = new Button(); //button to execute the final cost calculation
        btn.setText("Calculate"); 
        btn.setOnAction(new EventHandler<ActionEvent>() {
            @Override
            public void handle(ActionEvent event) {
                //event handler for button, executes the calculation

                final double Cost = perG * requiredG;
                System.out.println(Cost);
            }
        });


        VBox labello = new VBox();
        labello.getChildren().addAll(distLab, effLab, fuelLabel);
        VBox.setMargin(fuelLabel,new Insets(30, 0, 0, 0));
        labello.setPadding(new Insets(5, 0, 0, 20));


        HBox whole = new HBox();
        whole.getChildren().addAll(labello, textura);


        VBox root = new VBox();
        root.getChildren().addAll(whole, btn);
        VBox.setMargin(btn,new Insets(50, 0, 0, 140));
        root.setPadding(new Insets(30, 0, 0, 0));

        Scene scene = new Scene(root, 350, 250);

        primaryStage.setTitle("Fuel Cost Calculator");
        primaryStage.setScene(scene);
        primaryStage.show();

    }

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        launch(args);
    }

}

And thanks for trying, if you offer any advice at all

  • 1
    Can you please post the entire error message you recieved – Austin Mar 28 '20 at 17:17
  • 3
    Please [edit] your question to provide the full stack trace (formatted as code). Unfortunately, the `InvocationTargetException` tells us nothing of value. We need to know the causes of the exception. See [What is a stack trace, and how can I use it to debug my application errors?](https://stackoverflow.com/q/3988788/6395627) for more information. – Slaw Mar 28 '20 at 17:18
  • I ran your program with no csv file. I got maybe the same error. `double inputDistance = Double.parseDouble(distance.getText());` you are bascially trying to parse a double but you are passing an empty string. – SedJ601 Mar 28 '20 at 17:25

1 Answers1

1

You have a few problems.

First you should change

TextField distance = new TextField();
TextField eff = new TextField();

to

TextField distance = new TextField("0");
TextField eff = new TextField("0");

This will help your program run if there is no Excel file.

Your other problem is

BufferedReader csvReader = new BufferedReader(new FileReader(fuelCost));
dieselCost = Double.parseDouble(csvReader.readLine());
octaneCost = Double.parseDouble(csvReader.readLine());

Reading a CSV file is more complicated than just using a BufferedReader to get the file data and trying to read lines. You need to look into a CSV API. I personally like to use http://commons.apache.org/proper/commons-csv/.

SedJ601
  • 12,173
  • 3
  • 41
  • 59