簡體   English   中英

是否可以創建一個文本文件,然后在代碼的同一運行或運行時也讀寫這些文件? Java

[英]Is it possible to create a text file and then on the same run or runtime of the code also read and write in these files? Java

學期末我正在做一個 Uni 項目。 該程序是一個簡單的銀行系統。 我的問題是,當程序首次啟動時,它會創建一個“日志”文件夾。 然后,當使用構造函數創建帳戶 object 時,會在文件夾中創建一個新的 txt 文件,其中包含帳戶持有人的姓名。 到這里為止,我已經設法做到了。

問題是,當通過選項菜單關閉程序但在關閉程序之前,所有創建的對象(存儲在數組中)的所有詳細信息都按照它們存儲在 object 數組中的順序寫入各自的文件中但是在第一次運行時,文件被創建但沒有寫入任何內容。

然后在第二次運行時,如果我再次關閉程序,詳細信息將被正確寫入。 請給我一些建議,我在網上找不到任何相關信息?

import java.util.Scanner;
import java.io.*;

public class FileManagement {

  static String pathnameFile = "src\\Log";
  static File directory = new File(pathnameFile);
  static String[] allFiles = directory.list();

  public static void createFolder() {
    File logFile = new File(pathnameFile);
    if (!logFile.exists()) {
      logFile.mkdir();
    }
  }
  public static void writeFiles() throws IOException {
    FileWriter writer;
    for (int i = 0; i < allFiles.length; i++) {
      writer = new FileWriter(pathnameFile + "\\" + allFiles[i]);
      writer.write("accountName= " + eBanking.accounts[i].getAccountName() + "\n");
      writer.write("PIN= " + eBanking.accounts[i].getPIN() + "\n");
      writer.write("balance= " + Integer.toString(eBanking.accounts[i].getBalance()) + "\n");
      writer.write("Object ID stored in RAM= " + eBanking.accounts[i].toString() + "\n");
      writer.close();
    }
  }
//original method
  /*public static void readFiles() {
    Scanner reader;
    for (int i = 0; i < allFiles.length; i++) {
      reader = new Scanner(pathnameFile + allFiles[i]);
    }
  }*/
//My solution
  public static void readFiles() throws IOException{
        if(directory.exists() == false || allFiles == null) {
            return;
        }
        Scanner reader;
        File currentFile;
        String[] data = new String[4];
        for(int i = 0; i < allFiles.length; i++) {
            currentFile = new File(pathnameFile + "\\" +allFiles[i]);
            reader = new Scanner(currentFile);
            int count = 0;
            while(reader.hasNextLine()) {
                if(!reader.hasNext()) {
                    break;
                }
                reader.next();
                data[count] = reader.next();
                count++;
            }
            reader.close();
            String accountName = data[0];
            String PIN = data[1];
            int balance = Integer.parseInt(data[2]);
            eBanking.accounts[i] = new eBanking(accountName, PIN, balance);
        }
    }
}
import java.util.Scanner;
import java.io.*;

public class App {
    public static eBanking currentAccount;
    public static void mainMenu() throws Exception{
        while (true) {
            Scanner input = new Scanner(System.in);
            System.out.println("""
                --------------------------------------------------------
                1. Log in
                2. Register
                0. Exit.
                --------------------------------------------------------
                    """);
            int menuOption = input.nextInt();
            switch (menuOption) {
                case 1 -> {
                    System.out.println("Please enter your account name and PIN below.");
                    System.out.print("Account name: ");
                    String accountName = input.next();
                    System.out.print("PIN: ");
                    String PIN = input.next();
                    System.out.println();

                    for (int i = 0; i < eBanking.accounts.length; i++) {
                        if (accountName.equals(eBanking.accounts[i].getAccountName()) && PIN.equals(eBanking.accounts[i].getPIN())) {
                            eBanking.accounts[i].welcome();
                            currentAccount = eBanking.accounts[i];
                            break;
                        }
                    }
                    menu();
                }
                case 2 -> {
                    System.out.println("Please enter the account name, PIN and inital balance of your new account.");
                    System.out.print("Account name:");
                    String accountNameRegister = input.next();
                    System.out.print("PIN: ");
                    String registerPIN = input.next();
                    System.out.print("Initial balance: ");
                    int initialBalance = input.nextInt();

                    currentAccount = new eBanking(accountNameRegister, registerPIN, initialBalance);
                    menu();
                }
                default -> {
                    FileManagement.writeFiles();
                    System.exit(0);
                }
            }
        }
    }
    public static void menu() {
        Scanner input = new Scanner(System.in); 
        while (true) {
            System.out.println("""
                --------------------------------------------------------
                1. Show your balance.
                2. Withdraw money.
                3. Deposit money.
                4. Change your PIN.
                5. Transfer money to another person.
                0. Back.
                --------------------------------------------------------
                    """);
            int menuOption = input.nextInt();
            switch (menuOption) {
                case 1 -> {
                    currentAccount.showBalance();
                }
                case 2 -> {
                    System.out.println("Please enter the amount you want to withdraw: ");
                    int withdrawAmount = input.nextInt();
                    currentAccount.withdraw(withdrawAmount);
                }
                case 3 -> {
                    System.out.println("Please enter the amount you want to deposit: ");
                    int depositAmount = input.nextInt();
                    currentAccount.deposit(depositAmount);
                }
                case 4 -> {
                    currentAccount.changePIN();
                }
                case 5 -> {
                    System.out.println("Please enter the amount you want to send: ");
                    int amount = input.nextInt();
                    System.out.println("Please enter the account number you want to send the money to: ");
                    String transferAccount = input.next();// Me nextLine(); duhet ta shkruaj 2 here qe ta marri, duke perdor next(); problemi evitohet (E kam hasur edhe tek c++ kete problem)  
                    System.out.println("The amount of money is completed");
                    currentAccount.transfer(amount, transferAccount);
                }
                case 0 -> {
                    return;
                }
                default -> {
                    System.out.println("Please enter a number from the menu list!");
                }
            }
        }
    }
    public static void main(String[] args) throws Exception {
        FileManagement.createFolder();
        FileManagement.readFiles();
        mainMenu();
    }
}
import java.util.Scanner;
import java.io.*;

public class eBanking extends BankAccount {
    // Variable declaration
    Scanner input = new Scanner(System.in);
    private String accountName;
    private String accountID;

    public static eBanking[] accounts = new eBanking[100];

    // Methods
    public String getAccountName() {
        return accountName;
    }
    public void welcome() {
        System.out.println("---------------------------------------------------------------------------------------");
        System.out.println("Hello " + accountName + ". Welcome to eBanking! Your account number is: " + this.accountID);
    }
    public void transfer(int x, String str) {
        boolean foundID = false;
        withdraw(x);
        if (initialBalance == 0) {
            System.out.println("Transaction failed!");
        } else if (initialBalance < x) {
            for(int i = 0; i < numberOfAccount; i++) {
                if (str.equals(accounts[i].accountID)) {
                    accounts[i].balance += initialBalance;
                    System.out.println("Transaction completed!");
                    foundID = true;
                } 
            }
            if (foundID = false) {
                System.out.println("Account not found. Transaction failed. Deposit reimbursed");
                this.balance += initialBalance;
                return;
            }
        } else {
            for(int i = 0; i <= numberOfAccount; i++) {
                if (str.equals(accounts[i].accountID)) {
                    accounts[i].balance += x;
                    System.out.println("Transaction completed!");
                    foundID=true;
                    return;
                }
            }
            if (foundID = false) {
                System.out.println("Account not found. Transaction failed. Deposit reimbursed");
                this.balance += x;
                return;
            }
        }
    }
    // Constructors
    public eBanking(String name){
        int firstDigit = (int)(Math.random() * 10);
        int secondDigit = (int)(Math.random() * 10);
        int thirdDigit = (int)(Math.random() * 10);
        int forthDigit = (int)(Math.random() * 10);
        accountID = this.toString();

        PIN = Integer.toString(firstDigit) + secondDigit + thirdDigit + forthDigit; //Nuk e kuptova perse nese i jap Integer.toString te pares i merr te gjitha 
        balance = 0;                                                                //dhe nuk duhet ta perseris per the gjitha
        accountName = name;
        accounts[numberOfAccount] = this;
        numberOfAccount++;

        System.out.println("---------------------------------------------------------------------------------------");
        System.out.println(accountName + ": Your balance is " + balance + ", your PIN is: " + PIN + " and your account number is: " + accountID);
    }
    public eBanking(String name, String pin, int x){
        if (checkPIN(pin) == false) {
            System.out.println("Incorrect PIN format!");
            return;
        }
        accountID = this.toString();
        accountName = name;
        balance = x;
        PIN = pin;
        accounts[numberOfAccount] = this;
        numberOfAccount++;

        welcome();
    }
}
import java.util.Scanner;

public abstract class BankAccount {
    // Variable declaration
    protected String PIN;
    protected int balance;

    public static int numberOfAccount = 0;
    protected static int initialBalance; // E kam perdorur per te bere menune me dinamike sidomos per metoden transfer();

    //Methods
    //Balance
    public int getBalance() {
        return balance;
    }
    public void showBalance() {
        System.out.println("The total balance of the account is " + balance);
    }
    public void withdraw(int x) {
        initialBalance = balance;
        if (balance == 0) {
            System.out.println("The deduction has failed due to lack of balance!");
            return;
        }
        if (balance < x) {
            balance = 0;
            System.out.println("The deduction of " + initialBalance + " from your balance is completed!");
        } else {
            balance -= x;
            System.out.println("The deduction of " + x + " from your balance is completed!");
        }
    }
    public void deposit(int x) {
        balance += x;
        System.out.println("You have made a deposit of  " + x + " and your current balance is " + balance);
    }
    
    //PIN
    public String getPIN() {
        return PIN;
    }
    public void changePIN() {
        Scanner input = new Scanner(System.in);
        
        System.out.print("Please enter your previous PIN: ");
        String tryPIN = input.nextLine();

        if (tryPIN.equals(PIN)) {
            System.out.print("Please enter your new PIN: ");
            String newPIN = input.nextLine();
            if (checkPIN(newPIN) == false) {
                System.out.println("The PIN is not in the correct format!");
            } else {
                System.out.println("The PIN has been changed");
                PIN = newPIN;
            }
        } else {
            System.out.println("The PIN does not match!");
        }
    }
    protected static boolean checkPIN(String str) {
        boolean isValid;

        if(str.length() != 4) {
            isValid = false;
        } else {
            try {
                int x = Integer.parseInt(str);
                isValid = true;
            } catch (NumberFormatException e) {
                isValid = false;
            }
        }
        return isValid;
    }
    //Kjo metode duhet per testim
    public void getDetails() {
        System.out.println(balance + " and PIN " + PIN);
    }
}

我已經更新了帖子,展示了我是如何修復它並提供我所有的課程的。 請不要介意這些亂七八糟的代碼,因為我首先用一個開關嘗試它,然后在時機成熟時放棄它,並在我學會如何使用它后立即使用 GUI。 我也知道可以更好地組織課程,但 BankAccount 和 eBanking 是我在不同練習中使用的 2 個挽救課程。

我想我找到了解決辦法。 我只記得在使用 FileWriter 時,如果文件不存在,它會自動創建一個。 因此,我取消了每當創建新的 object 時創建文件的方法,現在每當程序關閉時,如果需要,就會創建文件,如果文件已經存在,則會被覆蓋。

我已經在我的程序中提供了所有當前代碼以及我在 FileManagment class 上實施的修復

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM