在3变量中添加3个字符串

时间:2015-10-15 09:23:17

标签: java user-interface

我的帐户类有3个变量来存储名称,ID和密码

我的方法addAcount()得到3个参数并将all传递给3变量。

问题是我无法将3参数项传递给3变量。

我的3变量声明:

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

这是我的方法:

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;
                                    }
                                }
                        }
                    }
            }
    }

任何帮助都会得到赞赏

2 个答案:

答案 0 :(得分:0)

访问所有元素 你的方法标题应该是: -

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];
  }
}

并称之为: -

addAccount(id,pass,name);

要访问特定位置的特定字符串: -

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

但是请注意,如果您使用的索引大于array.length,则直接访问数组{/ 3}}

答案 1 :(得分:0)

在这种情况下,您可以使用:

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;
                }
            }
        }

编辑:更改了代码,因此数组长度无关紧要