gpt4 book ai didi

java - 读写txt文件

转载 作者:行者123 更新时间:2023-11-30 10:49:47 24 4
gpt4 key购买 nike

我正在编写一段代码,读取文件 Banking.txt 并询问用户 ID 和密码,然后提示用户进行提款、存款或查询余额。余额将写入 Records.txt。程序在用户输入密码后终止,我不知道如何让它继续。请帮忙

public static void main(String[] args) throws FileNotFoundException {
File fil1 = new File("Banking.txt");
File fil2 = new File("Records.txt");
Scanner sc1 = new Scanner(fil1);
Scanner s1 = new Scanner(fil2);
String fname;
String mname;
String lname;
String uid = null;
int pin = 0;
double balance = 0;
java.io.PrintWriter output = new java.io.PrintWriter(fil2);
while (sc1.hasNext()) {
fname = sc1.next();
mname = sc1.next();
lname = sc1.next();
uid = sc1.next();
pin = sc1.nextInt();
balance = sc1.nextDouble();
BankRecord person = new BankRecord(fname,mname,lname,uid,pin,balance);
System.out.print(pin);
}

Scanner input = new Scanner(System.in);
System.out.print("Please enter a user ID: ");
String entereduid = input.nextLine();
if(entereduid.equals(uid)){
System.out.print("Please enter a Pin #: ");
String enteredpin = input.nextLine();
if(enteredpin.equals(pin)){
Scanner input2 = new Scanner(System.in);
System.out.print("press 1 to check balance, 2 for a deposit, or 3 for a withdrawal: ");
int ans = input.nextInt();
if(ans == 1){
System.out.print(balance);
output.println("The balance is now "+balance+"$.");
}
else if(ans == 2){
System.out.print("Your current balance is: " + balance+". Please enter an amount to deposit: ");
double dep = input.nextDouble();
balance = balance + dep;
System.out.print("You deposited "+dep+"$. Your new balance is: " + balance+"$.");
output.println("The balance is now "+balance+"$.");
}
else if(ans == 3){
System.out.print("Yor current balance is: "+balance+". Please enter an amount to withdrawl: ");
double wit = input.nextDouble();
balance = balance - wit;
System.out.print("You withdrew "+wit+"$. Your new balance is: "+balance+"$.");
output.println("The balance is now "+balance+"$.");

}}}}}

最佳答案

您正在以字符串形式从输入中读取 pin,但您以整数形式从文件中读取它;所以 Integer pin != String pin。您的 pin 永远不会被识别为正确的,因此您的程序会跳到最后。

尝试 new Scanner(System.in).nextInt() 将输入读取为整数。

所以我会改变这一行:

String enteredpin = input.nextLine();

为此:

Integer enteredpin = input.nextInt();

关于java - 读写txt文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35305679/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com