Java对象在for循环外返回null

时间:2014-05-26 19:15:36

标签: java arrays

public Account [] search(double bal){

boolean flag=false;
Account [] tmp = new Account[account.length];

//Loop until the end of the account array.
for(int i=0;i<account.length && account[i]!=null;i++)
{
if(account[i].getBal()==bal)
   {
           tmp[i]=account[i];
           System.out.println(tmp[i]);  //here returns correct value
           flag=true;
       }
   }


   System.out.println(tmp[0]);  //here returns null

   return tmp;
}

您好。我对Java很新。

System.out.println(tmp [i])返回正确的帐户ob​​j并打印值。

但是为什么System.out.println(tmp [0])在for循环外返回null?

3 个答案:

答案 0 :(得分:0)

如果我理解你的问题,你只是有点困惑 -

public Account[] search(double bal) {
  int flag = 0;
  Account[] tmp = new Account[account.length];

  // Loop until the end of the account array.
  for (int i = 0; i < account.length && account[i] != null; i++) {
    tmp[i] = account[i]; // I assume you wanted to "copy" account.
    if (account[i].getBal() == bal) {
      System.out.println(tmp[i]); // here returns correct
                                  // value
      flag = i;
    }
  }

  /* becasue 0 is not i */
  System.out.println(tmp[flag]); // use "flag"

  // Honestly, you should use -
  // http://docs.oracle.com/javase/7/docs/api/java/lang/System.html#arraycopy%28java.lang.Object,%20int,%20java.lang.Object,%20int,%20int%29
  // System.arraycopy(account, 0, tmp, 0, account.length);
  return tmp;
}

答案 1 :(得分:0)

    if(account[i].getBal()==bal)
   {
           tmp[i]=account[i];
           System.out.println(tmp[i]);  //here returns correct value
           flag=true;
       }
   }

如果在计数器i == 0时条件为假,则tmp [0]最终将为空。您可以将ArrayList与tmp变量一起使用,然后将其转换为Account数组,如下所示:

public Account [] search(double bal){


ArrayList<Account> tmp = new ArrayList<Account>();

for(int i=0;i<account.length && account[i]!=null;i++)
{
if(account[i].getBal()==bal)
   {
           tmp.add(account[i]);
           System.out.println(tmp[i]);  //here returns correct value
       }
   }

   Account resultArray[] = new Account[tmp.size()];
   resultArray = tmp.toArray(resultArray);

   return resultArray;
}

答案 2 :(得分:0)

如果第一个条件为假,则temp[0]始终为空。

 if(account[i].getBal()==bal)
   {
           tmp[i]=account[i];
           System.out.println(tmp[i]);  //here returns correct value
           flag=true;
       }

因为在此代码中,如果第一个条件只是正确的,它将进入"if"条件,然后将account[i]的值分配给temp[0]。否则它将永久无效。