Home > Mobile >  Trouble with project - new to java
Trouble with project - new to java

Time:02-22

I am working on a project for Uni, and I want to load file contents into local arrays which later print.

When the user chooses 1 to view the wallet, I want the program to display the crypto balance from the text file onto the console. However, my code is not doing that. I am very new to using buffered and I reverse engineered a previous assignment, so my code must be wrong.

My text file contains "BTC 1.3426 ETH 5.2519 XRP 158.5000"

Please ignore all the // code and see the sections for viewWallet() and readCryptoBalance().

import java.io.*;
import java.util.*;
public class Main {
    static Scanner userInputInt = new Scanner(System.in);
    static Scanner userInputString = new Scanner(System.in);
    static Scanner userInputDouble = new Scanner(System.in);

    public static void main(String[] args) { //throws Exception
        int userChoice = getUserChoice();
        switch (userChoice) {
            case 1:
                viewWallet();
                break;
        }
    }

    // This method asks and returns what the user wants to do
    public static int getUserChoice() {
        System.out.println("****************************************************************");
        System.out.println("****************************************************************");
        System.out.println("************ Crypto Wallet **********");
        System.out.println("****************************************************************");
        System.out.println("****************************************************************");
        System.out.println("");
        System.out.println("What do you want to do?");
        System.out.println("(1) View wallet");
        System.out.println("(2) Look up the balance of a given crypto");
        System.out.println("(3) Add new cryptos");
        System.out.println("(4) Remove an existing crypto");
        System.out.println("(5) Update wallet");
        System.out.println("****************************************************************");
        System.out.print("Please enter your choice (1, 2, 3, 4, or 5): ");
        return userInputInt.nextInt();
    }

    // This method is called for user choice 1
    public static void viewWallet() {
        double[] balance = readCryptoBalance();
        System.out.println(balance);
    }

    // This method reads and returns the crypto balances from the file
    public static double[] readCryptoBalance() {
       double[] temp = new double [100];
       int lineNumber =0;
       try{

           BufferedReader myFile = new BufferedReader (new FileReader("wallet.txt"));
           String sCurrentLine;
           while ((sCurrentLine = myFile.readLine()) != null){
               temp[lineNumber] =Integer.parseInt(sCurrentLine.split("\t")[1]);
               lineNumber  ;
           }
           myFile.close();
       } catch (IOException e){
           System.out.println("I/O exception error when reading");
       }
       double[] balance = new double[lineNumber];
       System.arraycopy(temp, 0, balance, 0, lineNumber);
       return balance;
    }
}

CodePudding user response:

You have a few mistakes (aside from missing curly braces that I added in my edit).

  1. sCurrentLine.split("\t") - There are two errors here. The first error is that you need to escape the slash character. Therefore, the correct expression should be "\\t". However, your file might not be tabbed delimited. Therefore, for space-delimited text, you should use "\\s", " ", or "\\s ". If you are not sure how many spaces, the last expression is the best because it will work with one-or-more spaces.

  2. Integer.parseInt(...) - This needs to be Double.parseDouble() because the values in the file are floating-point numbers, not integers.

  3. System.out.println(balance) inside viewWallet() is incorrect - That line displays the object, not the contents because arrays do not have a way to override toString(). So, you have to iterate through the balance array and display it contents. The simplest way is like this:

for(double value : balance) {
    System.out.println(value);
}

This will display all the values in the array in separate lines. If the array is empty, it will skip altogether.


Corrected code

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

public class Main {
    static Scanner userInputInt = new Scanner(System.in);
    static Scanner userInputString = new Scanner(System.in);
    static Scanner userInputDouble = new Scanner(System.in);

    public static void main(String[] args) { // throws Exception
        int userChoice = getUserChoice();
        switch (userChoice) {
        case 1:
            viewWallet();
            break;
        }
    }

    // This method asks and returns what the user wants to do
    public static int getUserChoice() {
        System.out.println("****************************************************************");
        System.out.println("****************************************************************");
        System.out.println("************ Crypto Wallet **********");
        System.out.println("****************************************************************");
        System.out.println("****************************************************************");
        System.out.println("");
        System.out.println("What do you want to do?");
        System.out.println("(1) View wallet");
        System.out.println("(2) Look up the balance of a given crypto");
        System.out.println("(3) Add new cryptos");
        System.out.println("(4) Remove an existing crypto");
        System.out.println("(5) Update wallet");
        System.out.println("****************************************************************");
        System.out.print("Please enter your choice (1, 2, 3, 4, or 5): ");
        return userInputInt.nextInt();
    }

    // This method is called for user choice 1
    public static void viewWallet() {
        double[] balance = readCryptoBalance();
        for(double value : balance) {
            System.out.println(value);
        }
    }

    // This method reads and returns the crypto balances from the file
    public static double[] readCryptoBalance() {
        double[] temp = new double[100];
        int lineNumber = 0;
        try {

            BufferedReader myFile = new BufferedReader(new FileReader("wallet.txt"));
            String sCurrentLine;
            while ((sCurrentLine = myFile.readLine()) != null) {
                String[] tokens = sCurrentLine.split("\\s ");
                temp[lineNumber] = Double.parseDouble(tokens[1]);
                lineNumber  ;
            }
            myFile.close();
        } catch (IOException e) {
            System.out.println("Error reading crypto balance: "   e.getMessage());
        }
        double[] balance = new double[lineNumber];
        System.arraycopy(temp, 0, balance, 0, lineNumber);
        return balance;
    }
}

Disclaimer: the contents of the file I created to test was exactly as the string provided by the OP (minus the double quotes) BTC 1.3426 ETH 5.2519 XRP 158.5000. Therefore, my solution assumed space-delimited string in a single line. Add a carriage return/line feed after each number to have distinct lines for the different crypto currency values.

CodePudding user response:

It is necessary to specify the entire path to the file, like this:

BufferedReader myFile = new BufferedReader(new FileReader("C:\\Users\\my-username\\MainProject\\wallet.txt"));

Note that it is very important to escape the slash character here again, like this: \\

Additionally, his code only returns the balance of the 1st value in the line. In case that's not what you wanted, I modified his code to now return all values of each row:

// This method reads and returns the crypto balances from the file
public static double[] readCryptoBalance() {
    double[] temp = new double[100];
    int tokenNumber = 0;
    try {

        BufferedReader myFile = new BufferedReader(new FileReader("C:\\Users\\my-username\\MainProject\\wallet.txt"));
        String sCurrentLine;
        while ((sCurrentLine = myFile.readLine()) != null) {
            String[] tokens = sCurrentLine.split("[A-Z]{3}\\s ");
            for (int i = 1; i < tokens.length; i  )
            {
                if (tokenNumber == 0)
                {
                    temp[0] = Double.parseDouble(tokens[i]);
                }
                else
                {
                    temp[tokenNumber] = Double.parseDouble(tokens[i]);
                }
                tokenNumber  ;
            }                
        }
        myFile.close();
    } catch (IOException e) {
        System.out.println("I/O exception error when reading");
    }
    double[] balance = new double[tokenNumber];
    System.arraycopy(temp, 0, balance, 0, tokenNumber);
    return balance;
}

Please note that I changed your variable name from lineNumber to tokenNumber as it is now collecting multiple tokens from each line.

I modified the wallet.txt as follows:

BTC 1.3426 ETH 5.2519 
XRP 158.5000

And the code gave me the following output:

1.3426
5.2519
158.5
  • Related