数组为null。没有从while循环获取信息 [英] Arrays are null. Not getting information from while loop

查看:158
本文介绍了数组为null。没有从while循环获取信息的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

下面的代码片段应该从文本文件中读取,检查文件中有多少个单词,以及有多少行,并且有了这些信息,它可以将第n个单词排序到合适的数组中。

  protected static void loadAccountInformationFromFile()throws Exception 
{
//这些变量控制所需的逻辑把单词放在正确的数组
int accountNumberCount = 1;
int firstNameCount = 2;
int lastNameCount = 3;
int balanceCount = 4;
int lastVariableCount = 5;
int sortCount = 1;


扫描器帐户=新扫描器(新文件(INPUT_ACCOUNT_FILE))。useDelimiter(,);

//使用字数获得第n个值
int wordCount = 0;
while(account.hasNext())
{
account.next();
wordCount ++;


//如果计数为零,则表示账户列表为空
if(wordCount == 0)
{
System.err .println(error:Account list empty。);
System.exit(1);
}

//用于测试字数统计功能:
// System.out.println(Number of words:+ wordCount);

int lineCount = wordCount / MAX_VALUES_PER_LINE;

//这些数组将被用于将帐户信息放在正确的位置
//使用lineCount创建无论大的数组都需要
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];


//如果我不关闭并打开一个新的扫描器,我得到一个编译器错误
account.close();
扫描器account2 =新扫描仪(新文件(INPUT_ACCOUNT_FILE))。useDelimiter(,);


{

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());

//测试它是否工作,但它只返回:
// [null,[Ljava.lang.String; @ 55f96302,null,null,null]
System.out.println(Arrays.toString(accountNumber));

//这个只返回[Ljava.lang.String; @ 55f96302
System.out.println(accountNumber [1]);

account2.close();



$ b

打开文件并正确计算单词没有问题。但是,到时候把这些单词放入适当的数组中是不行的,正如在注释文本中指出的那样。



我的问题是:为什么?我怎么能得到这个正常工作,而不使用BufferedWriter / BufferedReader?




基于一个答案,我纠正了逻辑中的一个缺陷,结果只有

运行:
错误:6
Java结果:1
BUILD SUCCESSFUL(总计时间:0秒)

这是修改过的代码:

pre $ $ $ $ $ $ $ $ $ $ $私人最终静态INT ACCOUNT_NUMBER_INDEX = 0;
private final int FIRST_INDEX = 1;
private final static LAST_INDEX = 2;
private final int BALANCE_INDEX = 3;
private final static int FREE_CHECKS_INDEX = 4;
private final int INT INTEREST_INDEX = 4;
private final static int MAX_VALUES_PER_LINE = 5;
private final static String INPUT_ACCOUNT_FILE =accountInfo.txt;
保护了静态字符串[]字段;
$ b $保护静态无效loadAccountInformationFromFile()抛出异常
{
//这些变量控制逻辑需要将单词放在正确的数组
int accountNumberCount = 0;
int firstNameCount = 1;
int lastNameCount = 2;
int balanceCount = 3;
int lastVariableCount = 4;
int sortCount = 1;


扫描器帐户=新扫描器(新文件(INPUT_ACCOUNT_FILE))。useDelimiter(,);

//使用字数获得第n个值
int wordCount = 0;
while(account.hasNext())
{
account.next();
wordCount ++;


//如果计数为零,则表示账户列表为空
if(wordCount == 0)
{
System.err .println(error:Account list empty。);
System.exit(1);
}

//用于测试字数统计功能:
// System.out.println(Number of words:+ wordCount);

int lineCount = wordCount / MAX_VALUES_PER_LINE;

//这些数组将被用于将帐户信息放在正确的位置
//使用lineCount创建无论大的数组都需要
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];


//如果我不关闭并打开一个新的扫描器,我得到一个编译器错误
account.close();
扫描器account2 =新扫描仪(新文件(INPUT_ACCOUNT_FILE))。useDelimiter(,);


{

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());

//测试它是否工作,但它只返回:
// [null,[Ljava.lang.String; @ 55f96302,null,null,null]
System.out.println(Arrays.toString(accountNumber));

//这个只返回[Ljava.lang.String; @ 55f96302
System.out.println(accountNumber [1]);

account2.close();


解决方案

这是因为在循环的每一次迭代中,增加所有的计数变量。

第一次进入循环时,有以下变量:

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

所以 sortCount == accountNumberCount 这意味着你把这个单词放到第二个位置(索引从0开始到数组)。



然后你增加所有上面的变量,并进行第二轮,有以下情况:

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

因此,在第二次迭代 sortCount 不再等于任何其他变量。同样的事情发生在进一步的迭代中,并且最终只有一个单词插入到五个数组中的一个中。




如果你想要做这个工作,我建议使用 ArrayLists (所以你不必担心数组索引或数组大小),而不是数组,只更改一个变量

  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;

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

int sortCount = 1;

//其他东西...

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());


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();

解决方案

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());

这篇关于数组为null。没有从while循环获取信息的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆