我一直在试图弄清楚如何将 Java 文件读入 JFrame。我需要制作一个框架并读取汽车的名称及其价格。从那里我需要计算根据用户输入的每月付款需要多长时间还清贷款。然后我必须计算利息成本是多少,利率也是由用户输入的。到目前为止,我的所有计算都正常工作,我的 JFrame 工作正常,当我单击按钮显示所有内容时,它工作正常。问题是不知道如何分别读取一个字符串和一个 double 值并进行所有计算,然后对文本文件中的任意数量的汽车和成本重复此过程。
这是我到目前为止的代码:
//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
所以 carLoan.txt 只是汽车的名称及其花费:
Honda Civic~10000
Porsche 911~50000
Chevrolet Blazer~20000
Toyota Camry~15000
然后我有另一个类,它包含我所有的构造函数、访问器、更改器(mutator)和计算方法。
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;
}
}
问题是我们取消了很多类(class),所以我的老师没有时间向我们解释如何正确执行此操作。如果有人可以帮助我,我将非常感激。如果需要的话,我还可以更深入地了解所有内容。
最佳答案
您可以使用 BufferedReader 来读取文件的每一行。然后,您可以使用 String#split
在 ~
分隔符上拆分 String
并解析各个元素,例如...
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();
}
打印...
Name | Price
Honda Civic | 10000
Porsche 911 | 50000
Chevrolet Blazer | 20000
Toyota Camry | 15000
关于java - 从 .txt 文件读取到 JFrame,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34170703/