为了帮助自己学习 Java,我正在使用 JForm GUI 创建一个二十一点程序,其中包括您可以创建的帐户并保持您用于投注每场比赛的运行余额。我有一个 BlackJackApp.JForm 类,它是主类。帐户存储在 .txt 文件中,并使用包含 readFile 和 writeFile 方法的 Account 类读取。我创建了一个名为 Accounts.txt 的示例 txt 文件,其中包含以下值:
约翰·多伊>>1000000
杰克·布莱克>>1
鲍勃·多尔>>987654321
(实际txt文件中的行之间没有空格)
我有一个读取文本文件并将这些值附加到 HashMap 的方法。这是我用于该方法的代码。
public void readFile()
{
accountsMap.clear();
BufferedReader br;
try
{
br = new BufferedReader(new FileReader("Accounts.txt"));
String nextLine = br.readLine();
while(nextLine != null)
{
String lineString[] = nextLine.split(">>");
Integer accountBalance = Integer.parseInt(lineString[1]);
System.out.println(lineString[0] + " " + lineString[1] + " " +
accountBalance);
accountsMap.put(lineString[0], accountBalance);
nextLine = br.readLine();
}
br.close();
}
catch(IOException frex)
{System.out.println("An error has occurred while reading the file");}
}
这是我为 JForm 类提供的相关代码,仅包含顶部以供参考
public class BlackjackApp extends javax.swing.JFrame {
Account a = new Account();
String account;
Integer accountBalance;
HashMap accountsMap = a.getAccountsMap();
public void fillAccountNameBox()
{
for (int i = 0; i < accountsMap.size(); i++)
{
accountNameBox.addItem((String) accountsMap.get(i));
}
}
public BlackjackApp() {
initComponents();
a.readFile();
fillAccountNameBox(); //fills comboBox component w/ list of hashMap keys
System.out.println(accountsMap.keySet());
for(int i = 0; i < accountsMap.size(); i++)
System.out.println(accountsMap.get(i));
}
system.out.println 代码用于调试。这是输出:
John Doe 1000000 1000000
Jack Black 1 1
Bob Dole 987654321 987654321
[Bob Dole, John Doe, Jack Black]
null
null
null
我的问题是:为什么我的 hashmap 放入了正确的键,但将它们的值保留为空?lineString 数组正确填充,整数 accountBalance 也是如此,但是当实际将键/值对放入 hashmap 时,它只放入键,即使 accountBalance 不为 null,它也将它们的值保留为 null。为什么是这样?我已经尝试在许多线程中搜索与此问题相关的建议,但他们的建议都没有对我有用。必须有一些我忽略的东西,但作为一个初学者,我很难认识到问题出在哪里。