-1

I have a text file that contains the following:

12345678,1234,100,DefaultUser

The third value "100" is a balance of money, what i need help doing is creating a withdraw method that changes that value according to the users input.

Can someone show an example of this so i can see how it could be done? This is what i have and i'm probably way off.

//Withdraw
public static void withdraw(){
    //Create a scanner object
    Scanner sc = new Scanner(System.in);

    // Get user input
    System.out.println("How much money would you like to withdraw?\n");
    System.out.print("Enter amount:\t");
    float amount = sc.nextInt();

    try {
        BufferedReader br = new BufferedReader(new FileReader("Data/users.txt"));
        BufferedWriter bw = new BufferedWriter(new FileWriter("Data/users.txt"));
        String[] userInfo = br.readLine().split(",");

        float currBalance = Integer.parseInt(userInfo[2]);
        float newBalance = currBalance - amount;

        userInfo[2] = ""+newBalance;
        bw.write(userInfo+"");

    } catch (FileNotFoundException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}

1 Answers1

0

The following example is a very rough version of what you are trying to achieve. Notice that the code places all the lines of a file into a Collection for temporary storage before completely rewriting the file to contain the new values.

This allows reading and writing of the file to occur separately.

public class Withdrawl {

    public static void main(String[] args) throws IOException {

        Scanner sc = new Scanner(System.in);

        // Get user input
        System.out.println("How much money would you like to withdraw?\n");
        System.out.print("Enter amount:\t");
        float amount = sc.nextInt();

        File input = new File("Data/users.txt");

        BufferedReader br = new BufferedReader(new FileReader(input));
        List<String> lines = new LinkedList<String>();

        //Write all lines to a Collection
        String line;
        while((line = br.readLine()) != null){
            lines.add(line);
        }
        br.close();

        //This could would need to find the actual user instead of using hardcoded 2
        String[] tokens = lines.get(0).split(",");
        float currentBalance = Float.parseFloat(tokens[2]);
        float newBalance = currentBalance + amount;
        tokens[2] = String.valueOf(newBalance);

        String finalString = "";
        String comma = "";
        for(String s: tokens){
            finalString += comma + s;
            comma = ",";
        }

        lines.set(0, finalString);

        FileWriter fw = new FileWriter(input);
        for(String out:lines){
            fw.write(out);
        }
        fw.flush();
        fw.close();

    }
}
Kevin Bowersox
  • 88,138
  • 17
  • 142
  • 176