Arrays are null. Not getting information from while loop

我的梦境 提交于 2019-12-13 21:32:38

问题


The following snippet of code is supposed to read from a text file, check how many words are in the file, and how many lines there are, and with that information it's supports to sort the nth word into it's appropriate array.

 protected static void loadAccountInformationFromFile() throws Exception 
    {
        // These variables control the logic needed to put words in the right array
        int accountNumberCount = 1;
        int firstNameCount = 2;
        int lastNameCount = 3;
        int balanceCount = 4;
        int lastVariableCount = 5;
        int sortCount = 1;


        Scanner account = new Scanner(new File(INPUT_ACCOUNT_FILE)).useDelimiter(",");

        // Using word count to get the nth value later
        int wordCount = 0;
        while(account.hasNext())
        {
            account.next();
            wordCount++;
        }

        // If the count is zero it means the account list is empty
        if (wordCount == 0)
        {
            System.err.println("error: Account list empty."); 
            System.exit(1);
        }

        // Used to test word count feature:
//       System.out.println("Number of words: " + wordCount);

        int lineCount = wordCount / MAX_VALUES_PER_LINE;

        // These arrays will be used to put the account information in the correct place
        // Using the lineCount to create the Array of however large it needs to be
        String[] accountNumber = new String[lineCount - 1];
        String[] firstName = new String[lineCount - 1];
        String[] lastName = new String[lineCount - 1];
        String[] balance = new String[lineCount - 1];
        String[] lastVariable = new String[lineCount - 1];


        // If I don't close and open a new Scanner I get a compiler error       
        account.close();                
        Scanner account2 = new Scanner(new File(INPUT_ACCOUNT_FILE)).useDelimiter(",");

        do
            {

                String[] temp1 = account2.next().split(",");
                String temp2 = "" + temp1;

                if (sortCount == accountNumberCount)
                {
                    accountNumber[sortCount] = temp2;
                }
                if (sortCount == firstNameCount)
                {
                    firstName[sortCount] = temp2;
                }
                if (sortCount == lastNameCount)
                {
                    lastName[sortCount] = temp2;
                }
                if (sortCount == balanceCount)
                {
                    balance[sortCount] = temp2;
                }
                if (sortCount == lastVariableCount)
                {
                    lastVariable[sortCount] = temp2;
                }

                accountNumberCount += 5;
                firstNameCount += 5;
                lastNameCount += 5;
                balanceCount += 5;
                lastVariableCount += 5;

                sortCount++;

                {

                }

            }
        while (account2.hasNext()); 

        // testing to see if it works, but it only returns:
        // [null, [Ljava.lang.String;@55f96302, null, null, null]
        System.out.println(Arrays.toString(accountNumber));

        // This one only returns [Ljava.lang.String;@55f96302
        System.out.println(accountNumber[1]);

        account2.close();
 }

It has no problem opening the file and counting the words properly. However, when it came time to put the words into the appropriate array it doesn't work, as indicated in the commenting out text.

My question is: Why? And how can I get this to work properly without using BufferedWriter / BufferedReader?


Based on an answer, I corrected a flaw in the logic only to end up with

run: error: 6 Java Result: 1 BUILD SUCCESSFUL (total time: 0 seconds)

Here's the modified code:

 public class Main 
 {
private final static int ACCOUNT_NUMBER_INDEX = 0;
private final static int FIRST_INDEX = 1;
private final static int LAST_INDEX = 2;
private final static int BALANCE_INDEX = 3;
private final static int FREE_CHECKS_INDEX = 4;
private final static int INTEREST_INDEX = 4;
private final static int MAX_VALUES_PER_LINE = 5;
private final static String INPUT_ACCOUNT_FILE = "accountInfo.txt";
protected static String[] fields;

 protected static void loadAccountInformationFromFile() throws Exception 
    {
        // These variables control the logic needed to put words in the right array
        int accountNumberCount = 0;
        int firstNameCount = 1;
        int lastNameCount = 2;
        int balanceCount = 3;
        int lastVariableCount = 4;
        int sortCount = 1;


        Scanner account = new Scanner(new File(INPUT_ACCOUNT_FILE)).useDelimiter(",");

        // Using word count to get the nth value later
        int wordCount = 0;
        while(account.hasNext())
        {
            account.next();
            wordCount++;
        }

        // If the count is zero it means the account list is empty
        if (wordCount == 0)
        {
            System.err.println("error: Account list empty."); 
            System.exit(1);
        }

        // Used to test word count feature:
 //                System.out.println("Number of words: " + wordCount);

        int lineCount = wordCount / MAX_VALUES_PER_LINE;

        // These arrays will be used to put the account information in the correct place
        // Using the lineCount to create the Array of however large it needs to be
        String[] accountNumber = new String[lineCount];
        String[] firstName = new String[lineCount];
        String[] lastName = new String[lineCount];
        String[] balance = new String[lineCount];
        String[] lastVariable = new String[lineCount];


        // If I don't close and open a new Scanner I get a compiler error       
        account.close();                
        Scanner account2 = new Scanner(new File(INPUT_ACCOUNT_FILE)).useDelimiter(",");

        do
            {

                String[] temp1 = account2.next().split(",");
                String temp2 = "" + temp1;

                if (sortCount == accountNumberCount)
                {
                    accountNumber[sortCount] = temp2;
                    accountNumberCount += MAX_VALUES_PER_LINE;
                }
                if (sortCount == firstNameCount)
                {
                    firstName[sortCount] = temp2;
                    firstNameCount += MAX_VALUES_PER_LINE;
                }
                if (sortCount == lastNameCount)
                {
                    lastName[sortCount] = temp2;
                    lastNameCount += MAX_VALUES_PER_LINE;
                }
                if (sortCount == balanceCount)
                {
                    balance[sortCount] = temp2;
                    balanceCount += MAX_VALUES_PER_LINE;
                }
                if (sortCount == lastVariableCount)
                {
                    lastVariable[sortCount] = temp2;
                    lastVariableCount += MAX_VALUES_PER_LINE;
                }

                sortCount++;

            }
        while (account2.hasNext()); 

        // testing to see if it works, but it only returns:
        // [null, [Ljava.lang.String;@55f96302, null, null, null]
        System.out.println(Arrays.toString(accountNumber));

        // This one only returns [Ljava.lang.String;@55f96302
        System.out.println(accountNumber[1]);

        account2.close();

回答1:


This happens because on every iteration of the loop, you increase all the count variables.

When coming to the loop for the first time you have the following variables:

accountNumberCount == 1
firstNameCount == 2
lastNameCount == 3
balanceCount == 4
lastVariableCount == 5
sortCount == 1

So sortCount == accountNumberCount and that means you put the word into accountNumber array to the second position (index starts from 0 on arrays).

Then you increase all the above variables and go for round two, having the following situation:

accountNumberCount == 6
firstNameCount == 7
lastNameCount == 8
balanceCount == 9
lastVariableCount == 10
sortCount == 2

Thus on second iteration sortCount no longer equals any of the other variables. Same thing happens on further iterations and you end up with only one word inserted into one of the five arrays.


If you want to make this work, I'd suggest using ArrayLists (so you don't have to worry about array indexes or array sizes) instead of arrays and to only change one variable per each iteration.

private static final int ACCOUNT_NUMBER_COUNT = 1;
private static final int FIRST_NAME_COUNT = 2;
private static final int LAST_NAME_COUNT = 3;
private static final int BALANCE_COUNT = 4;
private static final int LAST_VARIABLE_COUNT = 5;    

List<String> accountNumbers = new ArrayList<String>();
List<String> firstNames = new ArrayList<String>();
List<String> lastNames = new ArrayList<String>();
List<String> balances = new ArrayList<String>();
List<String> lastVariables = new ArrayList<String>();

int sortCount = 1;

// Other things...

do {
    if (sortCount == ACCOUNT_NUMBER_COUNT) {
        accountNumbers.add(temp2);
    } else if (sortCount == FIRST_NAME_COUNT) {
        firstNames.add(temp2);
    } else if (sortCount == LAST_NAME_COUNT) {
        lastNames.add(temp2);
    } else if (sortCount == BALANCE_COUNT) {
        balances.add(temp2);
    } else if (sortCount == LAST_VARIABLE_COUNT) {
        lastVariables.add(temp2);
    }

    if (sortCount < 5) {
        sortCount++;
    } else {
        sortCount = 1;
    }
} while (account2.hasNext());



回答2:


Personally I'd read line by line using BufferedReader, that way you do not need to calculate the number of lines,

try (BufferedReader br = new BufferedReader(new FileReader(file))) {
    String line;
    while ((line = br.readLine()) != null) {
       // process the line.
    }
}


来源:https://stackoverflow.com/questions/32856875/arrays-are-null-not-getting-information-from-while-loop

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!