'Reading from a .txt file into a JFrame

I'm stuck trying to figure out how to read from a Java file into a JFrame. I need to make a frame and read in the names of cars and how much they cost. From there I need to calculate how long it'll take to pay off the loan given a monthly payment inputted by the user. Then I have to calculate how much it will cost in interest with the interest rate also being inputted by the user. So far, I've got all my calculations working properly and my JFrame works and when I click my button to have everything displayed, it works. The problem is have no idea how to read in a String followed by a double separately and make all the calculations, then repeat this process for any number of cars and costs that are in the text file.

Here's the code I have so far:

//Make a JFrame
//Display a heading for car name, 
//loan amount, your monthly payment, how much it costs in interest 
//and the total price of the car.

//underneath you should have all of these things outputted and being    
//read in from carLoan.txt


package myName_B10_A04_FINAL;

import java.awt.BorderLayout;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
import java.util.Scanner;
import java.io.*;

public class CarLoanFrame extends JFrame implements ActionListener {

CarLoan reach = new CarLoan();

String carName;
int carPrice;

private JLabel lblMonthlyPayment = new JLabel("Monthly Payment: ");
private JLabel lblInterestRate = new JLabel("Interest rate (percentage): ");
private JTextField fldMonthlyPayment = new JTextField(15);
private JTextField fldInterestRate = new JTextField(15);

private JButton btnCalculate = new JButton("Calculate now!");

private JPanel inputPanel = new JPanel();
private JTextArea areaDisplay = new JTextArea(5, 2);

public CarLoanFrame() {
    setTitle("Car Loan Calculator");

    inputPanel.add(lblMonthlyPayment);
    inputPanel.add(fldMonthlyPayment);
    inputPanel.add(lblInterestRate);
    inputPanel.add(fldInterestRate);
    inputPanel.add(btnCalculate);

    getContentPane().add(inputPanel, BorderLayout.NORTH);
    getContentPane().add(areaDisplay, BorderLayout.CENTER);

    areaDisplay.setEditable(false);
    areaDisplay.setFont(new Font("Monospaced", Font.PLAIN, 12));
    btnCalculate.addActionListener(this);
}

@Override
public void actionPerformed(ActionEvent e) {

    try {
        File integerFile = new File("carLoan.txt");
        Scanner inFile = new Scanner(integerFile);
        inFile = inFile.useDelimiter("~|\r\n");

// First Row
        String car = "Car";
        String loan = "loan";
        String monthly = "monthly";
        String number = "number of";
        String total = "total";
        String cash = "Total";
// Second Row
        String amount = "amount";
        String payment = "payment";
        String NumberPayments = "payments";
        String interest = "Interest";
        String paid = "Paid";
// Third Row
        String breaker1 = "-------------------- ";
        String breaker2 = "------------ ";
        String breaker3 = "--------- ";
        String breaker4 = "------------ ";
        String breaker5 = "------------- ";
        String breaker6 = "--------------";
// Data Row
        String carName = "\n";
// First
        areaDisplay.append(String.format("%3s", car));
        areaDisplay.append(String.format("%30s", loan));
        areaDisplay.append(String.format("%10s", monthly));
        areaDisplay.append(String.format("%13s", number));
        areaDisplay.append(String.format("%14s", total));
        areaDisplay.append(String.format("%15s", cash));
// Second
        areaDisplay.append(String.format("\n%33s", amount));
        areaDisplay.append(String.format("%10s", payment));
        areaDisplay.append(String.format("%13s", NumberPayments));
        areaDisplay.append(String.format("%14s", interest));
        areaDisplay.append(String.format("%15s", paid));
// Third
        areaDisplay.append("\n" + breaker1);
        areaDisplay.append(breaker2);
        areaDisplay.append(breaker3);
        areaDisplay.append(breaker4);
        areaDisplay.append(breaker5);
        areaDisplay.append(breaker6);

// reading the next lines
        while (inFile.hasNext()) {
            carName = inFile.next();
            carPrice = inFile.nextInt();
                
            reach.setMake(carName);
            
            
            
// Actual output
        areaDisplay.append(carName);
        
        }
        
    } // try
    catch (FileNotFoundException e1) {
        System.exit(-1);
    } // catch (FileNotFoundException e)

} // actionPerformed()

public static void main(String[] args) {

    CarLoanFrame frame = new CarLoanFrame();
    frame.setSize(650, 600);
    frame.setLocation(720, 0);
    frame.setDefaultCloseOperation(EXIT_ON_CLOSE);
    frame.setVisible(true);
} // main()
} // CarLoanFrame class

So carLoan.txt is just the names of the cars and how much they cost:

Honda Civic~10000
Porsche 911~50000
Chevrolet Blazer~20000
Toyota Camry~15000

then I have another class that holds all of my constructor, accessor, mutator and calculation methods.

package myName_B10_A04_FINAL;


public class CarLoan {
double cost, loanAmount, interest, monthlyPayment, totalInterest;
int timesPayed;
String make, model;

//  Contstructor methods
public void variables() {
    cost = 0;
    loanAmount = 0;
    interest = 0;
    monthlyPayment = 0;
    totalInterest = 0;
    timesPayed = 0;
    make = "unknown";
    model = "unknown";
}

public void variables(String ma, String mo, double loanA){
    make = ma;
    model = mo;
    loanAmount = loanA;
    
    timesPayed = 0;
    cost = 0;
    interest = 0;
    monthlyPayment = 0;
    totalInterest = 0;
}

public void variables(double monthlyP, double interestR) {
    monthlyPayment = monthlyP;
    interest = interestR;
    
    cost = 0;
    loanAmount = 0;
    totalInterest = 0;
    timesPayed = 0;
    make = "unknown";
    model = "unknown";
}

//  Accessor methods
public double getCost() {
    return cost;    
}
public double getLoanAmount() {
    return loanAmount;
}
public double getInterest() {
    return interest;
}
public double getMonthlyPayment() {
    return monthlyPayment;
}
public double getTotalInterest() {
    return totalInterest;
}
public int getTimesPayed() {
    return timesPayed;
}
public String getMake() {
    return make;
}
public String getModel() {
    return model;
}

//  Mutator methods
private void setMake(String ma) {
    make = ma;
}
private void setModel(String mo) { 
    model = mo;
}
private void setLoanAmount(double lA) {
    loanAmount = lA;
}
private void setInterest(double i) {
    interest = i;
}
private void setMonthlyPayment(double mP) {
    monthlyPayment = mP;
}

//  Calculate methods
public double calculateTotalInterest() {
    double price = 0;
    timesPayed = 0;
    double costR = 0;
    
    while (costR >= 0) {
        costR = price - monthlyPayment; 
        double x = (costR * (interest/100.0)/12.0);
        totalInterest += x;
        costR += x;
        price = (costR * 100.0) / 100.0;
        
        timesPayed++;
    }
    return totalInterest;
}
}

The issue is that we had a lot of cancelled classes so my teacher didn't have time to explain to us how to do this properly. If someone could help me out that would be really appreciated. I can also go more in depth about everything if need be.



Solution 1:[1]

You could use a BufferedReader to read each line of the file. You could then use String#split to split the String on the ~ delimiter and parse the individual elements, for example...

try (BufferedReader br = new BufferedReader(new FileReader(new File("CarLoan.txt")))) {
    String text = null;
    System.out.printf("%-20s | %s%n", "Name", "Price");
    while ((text = br.readLine()) != null) {
        String parts[] = text.split("~");
        String name = parts[0];
        int price = Integer.parseInt(parts[1]);
        System.out.printf("%-20s | %d%n", name, price);
    }
} catch (IOException ex) {
    ex.printStackTrace();
}

which prints...

Name                 | Price
Honda Civic          | 10000
Porsche 911          | 50000
Chevrolet Blazer     | 20000
Toyota Camry         | 15000

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 MadProgrammer