I am working on a program to calculate mileage, fuel cost, and travel time when the user selects a vehicle from a combo box. It works well when reading from an array that I put in the program. But now I have to have it read the starting figures from a text file, put it into an array, and then do the calculations. I can get it to read from the file for the first vehicle but I get the Array Index Out Of Bounds Exception:3 on line 181 when I try the other 2 vehicles in the combo box. I have tried many other changes and just can't get it to work. Can anyone help? Here is my code:
import java.io.*;
import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.awt.BorderLayout;
import java.awt.Container;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JComboBox;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.JScrollPane;
public class RoadTripReadFile extends JFrame implements ActionListener {
//Variables declared to be visible to all methods
JTextArea output;
JTextField distanceTf;
JTextField mpgTf;
JTextField speedTf;
JTextField costTf;
JComboBox carCombo;
JButton calculateB;
JButton clearB;
String line;
String[] stats;
String[] cars = {" ", "GMC", "Toyota", "Chevy"};
double speed = 32;
NumberFormat formatter = new DecimalFormat("#0.00");
public RoadTripReadFile() {
}
//This constructor used when RoadTripFrame
//object is created from main() method and
//creates the panels and positioning of input/output areas
private RoadTripReadFile(String title) {
// uses super class constructor to set title
super(title);
//get the container to add the GUI components to
Container window = getContentPane();
JPanel northPanel = new JPanel();
//Panel layout will be a gridlayout
GridLayout northGrid = new GridLayout(6,2);
northPanel.setLayout(northGrid);
window.add(northPanel, BorderLayout.NORTH);
//create labels, JComboBox, input fields
JLabel titleL = new JLabel("Road Trip Calculator");
JLabel carLabel = new JLabel("Select Car:");
carCombo = new JComboBox(cars);
carCombo.setSelectedIndex(0);
carCombo.addActionListener(this);
northPanel.add(carLabel);
northPanel.add(carCombo);
JLabel distanceL = new JLabel("Distance:");
distanceTf = new JTextField(10);
JLabel mpgL = new JLabel("MPG:");
mpgTf = new JTextField(10);
JLabel speedL = new JLabel("Speed:");
speedTf = new JTextField(10);
JLabel costpergallonL = new JLabel("Cost:");
costTf = new JTextField(10);
// add components to the panel
northPanel.add(distanceL);
northPanel.add(distanceTf);
northPanel.add(mpgL);
northPanel.add(mpgTf);
northPanel.add(speedL);
northPanel.add(speedTf);
northPanel.add(costpergallonL);
northPanel.add(costTf);
//create buttons
calculateB = new JButton("Calculate");
calculateB.addActionListener(this);
clearB = new JButton("Clear");
clearB.addActionListener(this);
//add buttons to panel
northPanel.add(calculateB);
northPanel.add(clearB);
// create the text area for the output
// and make it a scrolling pane
output = new JTextArea(200,200);
JScrollPane scrollPane = new JScrollPane(output);
//add the output and ScrollPane to the Center areas
window.add(scrollPane, BorderLayout.CENTER);
}
//reads from a text file for car data
public void readFromFile(String readFromFileName) throws IOException {
File carFile = new File(readFromFileName);
FileReader reader = new FileReader(carFile);
BufferedReader buffReader = new BufferedReader(reader);
String vehicleData = buffReader.readLine();
stats = vehicleData.split(" ");
for (int i = 0; i<stats.length; i++){
}
}
//This method is called when the buttons are pressed
public void actionPerformed(ActionEvent event) {
boolean errorOccured = false;
Object source = event.getSource();
//if the JComboBox item is selected,
//populate the text fields with the correct data
if (source instanceof JComboBox){
//clear the text area
output.setText(null);
if (carCombo.getSelectedItem().equals("GMC")){
distanceTf.setText(stats[0]);
mpgTf.setText(stats[1]);
speedTf.setText("32");
costTf.setText(stats[2]);
}
else if (carCombo.getSelectedItem().equals("Toyota")){
distanceTf.setText(stats[3]);
mpgTf.setText(stats[4]);
speedTf.setText("32");
costTf.setText(stats[5]);
}
else if (carCombo.getSelectedItem().equals("Chevy")){
distanceTf.setText(stats[6]);
mpgTf.setText(stats[7]);
speedTf.setText("32");
costTf.setText(stats[8]);
}
}
//if the Calculate button is clicked,get text and parse it,
//if an error is made, let user know to correct it,
//then calculate the trip data and print the output,
//output and calculations will be based on increments of 10,
//else if Clear is clicked, clear the text fields;
else if (source instanceof JButton){
if (source == calculateB) {
String distanceEntered = distanceTf.getText();
double distance = 0;
try {
distance = Double.parseDouble(distanceEntered);
} catch (NumberFormatException e) {
JOptionPane.showMessageDialog(this,
"Please enter valid number for distance.",
"Error",JOptionPane.ERROR_MESSAGE);
errorOccured = true;
}
String mpgEntered = mpgTf.getText();
double mpg = 0;
try {
mpg = Double.parseDouble(mpgEntered);
}catch (NumberFormatException e) {
JOptionPane.showMessageDialog(this,
"Please enter valid number for miles per gallon.",
"Error",JOptionPane.ERROR_MESSAGE);
errorOccured = true;
}
String speedEntered = speedTf.getText();
double speed = 0;
try {
speed = Double.parseDouble(speedEntered);
}catch (NumberFormatException e) {
JOptionPane.showMessageDialog(this,
"Please enter valid number for speed.",
"Error",JOptionPane.ERROR_MESSAGE);
errorOccured = true;
}
String costEntered = costTf.getText();
double cost = 0;
try {
cost = Double.parseDouble(costEntered);
}catch (NumberFormatException e) {
JOptionPane.showMessageDialog(this,
"Please enter valid number for fuel cost per gallon.",
"Error",JOptionPane.ERROR_MESSAGE);
errorOccured = true;
}
if (errorOccured == true)
return;
double miles;
output.setText("Distance\tGallons Used\tFuel Cost\tHours and Seconds\n\n");
for (miles = 10; miles <= distance; miles = miles + 10){
double gallonsUsed = miles / mpg;
double fuelCost = gallonsUsed * cost;
double travel = miles / speed;
double hours = travel;
double decimalValue = miles % speed;
double seconds = (decimalValue / speed) * 3600;
output.append(miles + "\t");
output.append(formatter.format(gallonsUsed) + "gallons\t");
output.append("$" + formatter.format(fuelCost) + "\t");
output.append(hours + " hours, and " + seconds + " seconds\n");
}
output.setCaretPosition(0);
}
else if (source instanceof JButton){
if (source == clearB) {
distanceTf.setText("");
mpgTf.setText("");
speedTf.setText("");
costTf.setText("");
output.setText("");
}
}
}
}
//Entry point (main method) for the program
public static void main(String []args){
//create the RoadTripReadFile object, set the size, and make it visible
RoadTripReadFile frame = new RoadTripReadFile("Road Trip Calculator");
try {
frame.readFromFile("vehicle.txt");
} catch (IOException e){
e.printStackTrace();
}
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setSize(500, 500);
frame.setVisible(true);
}
}
Thanks.