为什么我的方法会覆盖数组中的位置

问题描述 投票:0回答:1

所以我在这里有此方法

    while(oMenu == 1 || oMenu == 2){
            oMeny = Kbd.readInt("\nClick 1 to make an account\nClick 2 to login\nClick 3 to exit the program");
            if(oMeny == 1){
                for(int i = 0; Account[i] != null; i++){
                    if(Account[i] == null){
                        pos = i;
                    }
                }

                Account[pos] = new Account();


            }

            if(oMeny == 2){
                String s = Kbd.readString("Input your accountnumber: ");
                for(int i = 0; Account[i] != null; i++){
                    if(Account[i] != null && s.equals(Account[i].getAccountNumber())){
                        System.out.println("Welcome!");
                         // Here is rest of my code , the "inner" menu that works menyMetod(iMeny,mMeny);
                    }
                    else{
                        System.out.println("There are no accounts with that given accountnumber!");  
                    }
                }                
            }

        }
    } 

我想了解为什么我要访问oMeny == 1并创建2个帐户为什么我似乎无法访问我创建的第一个帐户,而访问最近的一个帐户?看来我的数组以某种方式“覆盖”了第一个空位置。基本上,我想在数组中找到第一个空位,因此在第一种情况下,它始终是索引0,然后在下一次再次创建帐户时,逻辑上应该是索引1。

编辑:这是我的Account类代码

public class Account{

private int money, transactions;
private String AccountNumber;

public Account(){
    money = Kbd.readInt("\nHow much money do you want to put in?");
    AccountNumber = Kbd.readString("\nWhat account number do you want?");
}
java arrays while-loop logic account
1个回答
0
投票
您没有显示pos的声明或初始化,所以我认为它不符合您的期望,因为您没有进入其中Account [i]为null来设置pos的for循环。试试这个

if(oMenu == 1){ int pos = 0; while (Account[pos] != null && pos < Account.length) pos++; if (pos < Account.length) Account[pos] = new Account(); else{ //expand array and add account or throw error } }

© www.soinside.com 2019 - 2024. All rights reserved.