2016-02-10 133 views
2

我在写一个代码,读入文件Banking.txt,并要求输入用户标识,然后提示用户进行提款,存款或支票余额。余额将写入Records.txt。该程序终止后,用户进入引脚,&我不知道如何使其继续。请帮助读取和写入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+"$."); 

}}}}} 
+0

考虑使用一些方法能够反映你的逻辑 - 如果有必要出先写逻辑在纸上 –

+1

压痕的位将有所帮助 – peter

回答

1

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

尝试new Scanner(System.in).nextInt()以整数形式读取输入。

所以我想改变这一行:

String enteredpin = input.nextLine(); 

这样:

Integer enteredpin = input.nextInt(); 
+1

,你正在做一个新的'Scanner'实例有什么特别的原因吗?使用输入实例有什么问题? –

+0

@lane - 你是对的。 '新的扫描仪...'只是样板文件 - 如果已经创建好了,最好使用相同的扫描仪实例。将更新 – nlloyd

0

如果我理解正确的话,你想要写 “人” 对象(即BankRecord的实例)到一个文件?因为我不知道该类中有什么方法,所以我会假设有一个合适的toString()覆盖。我还会假设你正试图写入你的主目录。

 Path dir = Paths.get(URI.create("file:///"+System.getProperty("user.home")+System.getProperty("file.separator")+"BankRecords.txt")); 
     try (BufferedWriter bfr = Files.newBufferedWriter (dir, Charset.forName("UTF-8"))) { 
      String contents = person.toString(); 
      bfr.write(contents, 0, contents.length()); 
     } 
     catch (IOException ioe) { 
      System.err.println(ioe.getMessage()); 
     }