简体   繁体   中英

read lines from external file and store elements in array

I am new here so please show some patience. I am trying to read the data from an external file and store the info in 2 arrays. The file looks like this:

0069     723.50 
0085     1500.00
0091     8237.31

I am using 2 scanners to read the input and I think they work ok because when I try to print, the result looks ok. My first problem is that I am able to read the first numbers on the list using nextInt(), but cannot use nextDouble() for the double ones as I get the "java.util.InputMismatchException" message. For that reason I read it as a String. The part with the other two scanners is supposed to do what the first parts should do, for a different input file, but the problem is the same. My next and biggest problem, until now, is that am not able to store the values from the two columns in two distinct arrays. I have tried several ways (all commented) but all fail. Please help and thanks. Here is my code:

import ui.UserInterfaceFactory;
import java.io.PrintStream;
import java.util.Arrays;
import java.util.Scanner;
import ui.UIAuxiliaryMethods;

public class Bank {
    static final int MAX_NUMBER_OF_ACCOUNTS = 50;

    PrintStream out;

    Bank(){
        UserInterfaceFactory.enableLowResolution(true);
        out = new PrintStream(System.out);
    }

    void readFiles(){
        Scanner balanceFile = UIAuxiliaryMethods.askUserForInput().getScanner();
        while(balanceFile.hasNextLine()){
            String balance_Line = balanceFile.nextLine();
            Scanner accountsFile = new Scanner(balance_Line);

            int account = accountsFile.nextInt();                       //works
            out.printf("%04d ",account);


            /*int [] accounts_array = new int [MAX_NUMBER_OF_ACCOUNTS];         //does not store the values properly
            int account = accountsFile.nextInt();
            for(int j=0; j < accounts_array.length; j++){

                accounts_array[j] = account;

            }*/

            /*int [] accounts_array = new int [MAX_NUMBER_OF_ACCOUNTS];         //java.util.InputMismatchException
                for(int j=0; j < accounts_array.length; j++){

                    accounts_array[j] = accountsFile.nextInt();
                    //out.printf("%04d \n",accounts_array[j]);
                }*/


            String balance = accountsFile.nextLine();                       //problem declaring balance as a double
            out.printf("%s\n",balance);

            /*String [] balance_array = new String [MAX_NUMBER_OF_ACCOUNTS];            //java.util.NoSuchElementException
            for(int j=0; j < balance_array.length; j++){
                accountsFile.useDelimiter(" ");

                balance_array[j] = accountsFile.next();
                //out.printf("%04d \n",accounts_array[j]);
            }*/
        }

        Scanner mutationsFile = UIAuxiliaryMethods.askUserForInput().getScanner();
        while(mutationsFile.hasNext()){

            String mutation_Line = mutationsFile.nextLine();
            Scanner mutatedAccountsFile = new Scanner(mutation_Line);


            int mutated_account = mutatedAccountsFile.nextInt();
            out.printf("%04d ",mutated_account);


            int action = mutatedAccountsFile.nextInt();     //deposit or withdrawal
            /*if (action == 1){

            }else{

            }*/
            out.printf(" %d ",action);

            /*Double amount = mutatedAccountsFile.nextDouble();
            out.printf(" %5.2f ",amount);*/
            String amount = mutatedAccountsFile.nextLine();
            out.printf("%s\n",amount);
        }

    }

    void start(){
        new Bank();readFiles();
    }


    public static void main(String[] args) {
        new Bank().start();
    }
}   

The InputMismatchException occurs because you try to read a double using the nextInt() function. To solve this issue, you can first read the tokens as Strings using the next() function and convert them appropriately.

while(mutationsFile.hasNext()){
    mutation_Line = mutationsFile.next();
    if(mutation_Line.indexOf(".") == -1)
        //token is int
    else
        //token is double
}

Since you already know what the contents of the two columns are, you can store the integers and doubles in two lists and then, if you want, get them into an array.

List<Integer> intList = new ArrayList<Integer>();
List<Double> doubleList = new ArrayList<Double>();

Now replace the if statements in the first snippet with this:

if(mutation_Line.indexOf(".") == -1)
    intList.add(new Integer(Integer.parseInt(mutation_Line)));
else
    doubleList.add(new Double(Double.parseDouble(mutation_Line)));

In the end, you can get them into arrays:

Object[] intArr = intList.toArray(),
         doubleArr = doubleList.toArray();
//display the contents:
for(int i=0; i<intArr.length; i++)
out.printf("%04d\t%.2f\n", Integer.parseInt(intArr[i].toString()),
                       Double.parseDouble(doubleArr[i].toString()));

OUTPUT :

0069    723.50
0085    1500.00
0091    8237.31

First off, you don't need to use 2 scanners. The Scanner object is simply reading your file, one scanner is plenty to accomplish the task of reading a file.

If you're trying to read the integers/doubles from file and are having trouble with nextInt() and nextDouble(), consider a different approach to parsing (eg parse the line into a string, split the line into 2 parts based on a space character, then trim both resulting strings and convert to respective integers/doubles).

Now back to the Scanner parsing the two values, remember first that when you use a next() or nextInt(), etc. those methods consume the next respective token. So parsing a line as a string from the file into another Scanner object is redundant and unnecessary in this case.

If you know your max number of accounts, and it's simply 50, then go ahead an allocate that prior to the while loop.

Here's an alternative approach with the code you posted.

public class App {
    static int MAX_NUMBER_OF_ACCOUNTS = 50;
    static PrintStream out;
    static void readFiles() {
        Scanner balanceFile = null;
        try {
            balanceFile = new Scanner(new File("C:\\Users\\Nick\\Desktop\\test.txt"));
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        if (balanceFile == null)
            return;
        int [] accounts_array = new int [MAX_NUMBER_OF_ACCOUNTS];
        double [] balance_array = new double [MAX_NUMBER_OF_ACCOUNTS];
        int currentIndex = 0;
        while (balanceFile.hasNextLine()) {
            int account = balanceFile.nextInt();
            double balance = balanceFile.nextDouble();
            System.out.print("acc = " + account + " ");
            System.out.println("bal = " + balance);
            //out.printf("%04d ", account);
            accounts_array[currentIndex] = account;
            //out.printf("%s\n", balance);
            balance_array[currentIndex] = balance;
            currentIndex++;
        }
        balanceFile.close();
    }
    static void start() {
        readFiles();
    }
    public static void main(String[] args) {
        start();
    }
}

Please note the excessive use of static could also be avoided in the future, but for the sake of the example it spread like the plague.

As you can see in the logic leading up to the while loop, the scanner object is made from a file I copied your example data into a file on my desktop. The arrays are allocated prior to the while loop (note: see @progy_rock and their use of ArrayList's - may help improve your code in the long run). And finally, note the index count to move the position along in the array to which you are inserting your lines to.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM