如何要求用户输入帐号,然后从文本文件中 return 他的余额
how to ask the user to enter account number and then return his balance from a text file
我有一个包含两列的文本文件,一列用于帐号,另一列用于余额。
我想向用户询问他的帐号并从文本中获取他的余额。
我有存款和取款之类的方法,我想将其应用于用户的余额,然后更新文本文件。最好的方法是什么?
我应该使用数组吗?或者有更简单的方法吗?
文本文件应该是这样的
1001 50.67
1002 500.32
1003 63.63
1004 953.53
1005 735.22
使用数组不是解决此问题的实用方法。我制作了一个示例程序,它在没有数组的情况下执行上述操作。要做到这一点 运行,请确保您的帐户文件是 names BankAccounts.txt
import java.io.*;
import java.util.*;
public class BankAccount {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
File dir = new File("BankAccounts.txt");
System.out.println("Please enter your bank account number.");
String bankNumber = input.nextLine();
input.close();
System.out.println("Your Balance is: "
+ balanceFromAccount(bankNumber, dir));
}
public static String balanceFromAccount(String accountNumber, File file) {
String tempNumber = "";
int i;
try {
BufferedReader br = new BufferedReader(new FileReader(file));
String line = null;
while ((line = br.readLine()) != null) {
for (i = 0; line.charAt(i) != ' '; i++) {
tempNumber = tempNumber.concat(line.substring(i, i + 1));
}
if (tempNumber.equals(accountNumber)) {
return line.substring(i + 1);
}
tempNumber = "";
}
br.close();
} catch (Exception e) {
}
return "Not Found!";
}
}
该程序只是打开文件,找到每个银行帐号,检查它是否是所需的帐号,然后 returns 如果是,则计算值。如果不是,它会显示 "Not Found!"
我有一个包含两列的文本文件,一列用于帐号,另一列用于余额。 我想向用户询问他的帐号并从文本中获取他的余额。 我有存款和取款之类的方法,我想将其应用于用户的余额,然后更新文本文件。最好的方法是什么? 我应该使用数组吗?或者有更简单的方法吗?
文本文件应该是这样的
1001 50.67
1002 500.32
1003 63.63
1004 953.53
1005 735.22
使用数组不是解决此问题的实用方法。我制作了一个示例程序,它在没有数组的情况下执行上述操作。要做到这一点 运行,请确保您的帐户文件是 names BankAccounts.txt
import java.io.*;
import java.util.*;
public class BankAccount {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
File dir = new File("BankAccounts.txt");
System.out.println("Please enter your bank account number.");
String bankNumber = input.nextLine();
input.close();
System.out.println("Your Balance is: "
+ balanceFromAccount(bankNumber, dir));
}
public static String balanceFromAccount(String accountNumber, File file) {
String tempNumber = "";
int i;
try {
BufferedReader br = new BufferedReader(new FileReader(file));
String line = null;
while ((line = br.readLine()) != null) {
for (i = 0; line.charAt(i) != ' '; i++) {
tempNumber = tempNumber.concat(line.substring(i, i + 1));
}
if (tempNumber.equals(accountNumber)) {
return line.substring(i + 1);
}
tempNumber = "";
}
br.close();
} catch (Exception e) {
}
return "Not Found!";
}
}
该程序只是打开文件,找到每个银行帐号,检查它是否是所需的帐号,然后 returns 如果是,则计算值。如果不是,它会显示 "Not Found!"