Storing array of strings in specifies variables respectively

前端 未结 2 911
轮回少年
轮回少年 2021-01-24 15:10

I\'m a beginner at JAVA and I\'m writing this code that\'s supposed to receive an array of strings and store every string (array element) in the specified variables respectively

相关标签:
2条回答
  • 2021-01-24 15:42
    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();        
        }
    }
    
    0 讨论(0)
  • 2021-01-24 15:54

    There's a much easier way to do what you're trying to do, using String's split() method:

    static void func (){
        String[] split = sss.split(",");
        if (split.length < 5) {
            // this means some error in the input, need to handle
        }  
        male=split[0];
        blood=split[1];
        age=split[2];
        nat=split[3];
        dis=split[4];
    }
    
    0 讨论(0)
提交回复
热议问题