-1

My Account class have 3 variable to store name, id and password

and my method addAcount() get 3 parameter and pass all into the 3 variable.

The problem is i cant pass the 3 parameter item into the 3 variable.

my 3 variable declaration :

private String[] id = new String[100];
private String[] pass = new String[100];
private String[] name = new String[100];

here's my method:

public void addAccount(String id, String pass, String name){
        for(int i=0; i < this.id.length;i++){
            if(this.id[i]==null){
                this.id[i]=id;
                    for(int a = 0; a <this.pass.length;a++){
                        if(this.pass[a]==null){
                            this.pass[a]=pass;
                                for(int b=0;b<this.name.length;b++){
                                    if(this.name[b]==null){
                                        this.name[b]=name;
                                            break;
                                    }
                                }
                        }
                    }
            }
    }

Any Help will be Appreciated

Kai Loon
  • 31
  • 1
  • 7

2 Answers2

0

To access all elements Your method header shoud be :-

public void addAccount(String[] id, String[] pass, String[] name){
 //your code here
 // By looping over array you can get the strings in it
  for(int i = 0 ; i < id.length ; i++){
    String str_id = id[i];
  }
}

And to call it :-

addAccount(id,pass,name);

To access specific string at specific position :-

String str_pass = pass[5];//by his you will get the 6th element(zero base indexing )

But be aware if you direct access the array if the index you use greater than array.length you will get array out of boundary exception

Community
  • 1
  • 1
karim mohsen
  • 2,164
  • 1
  • 15
  • 19
0

In this situation you can use this:

public void addAccount(String id, String pass, String name)
        {     
          //These for loops look up the first empty spot in the array and
          //insert the chosen parameter in that spot once

            //Add ID to array
            for (int i = 0; i < this.id.length; i++)
            {
                if (this.id[i] == null)
                {
                    this.id[i] = id;
                    i = this.id.length;
                }
            }
            //Add Pass to array
            for (int a = 0; a < this.pass.length; a++)
            {
                if (this.pass[a] == null)
                {
                    this.pass[a] = pass;
                    a = this.pass.length;
                }
            }
            // Add name to array
            for (int b = 0; b < this.name.length; b++)
            {
                if (this.name[b] == null)
                {
                    this.name[b] = name;
                    b = this.name.length;
                }
            }
        }

Edit: changed the code so the array length won't matter

Bret
  • 1