存储字符串数组分别指定变量

时间:2016-04-20 14:31:43

标签: java arrays string

我是JAVA的初学者,我正在编写这段代码,该代码应该接收一个字符串数组,并将每个字符串(数组元素)分别存储在指定的变量中。但它只存储第一个元素。以下是代码:

package ontoretrive;

import org.apache.commons.lang3.ArrayUtils;

public class j {
static String sss= "male,O+,45,saudi,brain_diseases";
static int size =sss.length();

static String male="";
static String blood="";
static String age="";
static String nat="";
static String dis="";
static char temp;
static void func (){
    char[] charArray = sss.toCharArray();
    Character[] charObjectArray = ArrayUtils.toObject(charArray);
    int count=0;
    int x=0;
    while (x< size){
        temp =charObjectArray[x];
while(temp!=','&&count==0){
                male=male+temp;
                x++;
                temp =charObjectArray[x];}
x++;
temp =charObjectArray[x];

count++;            

while(temp!=','&&count==1){
        blood=blood+temp;
        x++;
        temp =charObjectArray[x];}
x++;
temp =charObjectArray[x];
count++;            

while(temp!=','&&count==2){
        age=age+temp;
        x++;
        temp =charObjectArray[x];
}x++;
temp =charObjectArray[x];
count++;            

while(temp!=','&&count==3){
        nat=nat+temp;
        x++;
        temp =charObjectArray[x];
}x++;
temp =charObjectArray[x];
count++;            


while(temp!=','&&count==4){
        dis=dis+temp;
        x++;
        //temp =charObjectArray[x];
        }
x++;
// temp =charObjectArray[x];
count++;    }

System.out.println(male);//end while1
System.out.println(blood);//end while1
System.out.println(age);//end while1
System.out.println(nat);//end while1
System.out.println(dis);//end while1

}//end func
public static void main(String[] args) {
    System.out.println("dis1");
    func();
   System.out.println(male);//end while1

    //System.out.println("dis3");


}
}    //end class

2 个答案:

答案 0 :(得分:0)

使用String的split()方法,可以更轻松地完成您尝试做的事情:

Salesforce

答案 1 :(得分:0)

public class j {

    static String sss = "male,O+,45,saudi,brain_diseases";
    static int size = sss.length();

    //I suggest you not to give them a start value or set them as null
    static String male = "";
    static String blood = "";
    static String age = "";
    static String nat = "";
    static String dis = "";

    static void func() {

        //it uses the "," character to breaks the string sss into pieces
        //so became into "male","O+","45","saudi","brain_diseases"
        String[] pieces = sss.split(",");

        //pieces[0] is the first piece so = "male"
        //pieces[1] is the second "O+" and so on
        male = pieces[0];
        blood = pieces[1];
        age = pieces[2];
        nat = pieces[3];
        dis = pieces[4];

        System.out.println(male);
        System.out.println(blood);
        System.out.println(age);
        System.out.println(nat);
        System.out.println(dis);

    }

    public static void main(String[] args) {

        func();        
    }
}