0

I'm new to Java, and I had a quick question.

I have an array named studentInfo[0] that I created from:String studentInfo[] = line.split(","); I would like to make another array from it's first index.

In other words. I have the array studentInfo that lets say looks like this: "a,b,c,d,
a1,b1,c1,d1, a2,b2,d2,c2 etc... " I want another array that takes all the "a" in my other array. Example: "a,a1,a2 etc..."

How would I do this?

I have tried System.arraycopy(studentInfo, 0, array, 0, studentInfo.length); But doesn't seem to work because it does not just give me the first index.

FYI my code is in a while loop which loops every time it hits a new line. See below:

 while ((line = reader.readLine()) != null) {
            String studentInfo[] = line.split(",");
            String array[] = new String[0];
      }

Thank you!

1
  • 2
    "But it does not seem to work" - What is it doing? What shouls it be doing? "doesnt seem to work" doesnt help us figure out the problem. HOW is it not working? "FYI my code is in a while loop which loops every time it hits a new line." - You should probably show this code Commented Nov 17, 2014 at 18:31

3 Answers 3

1

I would do something like.

String[] studentInfoA = new String[50] //You can put the size you want.

    for(int i=0; i<studentInfo.length-1; i++){
        if(studentInfo[i].substring(0,1).equals("a")){
           studentInfoA[i]=studentInfo[i];
        }
    }

i would recommend Vimsha's answer better but since you are learning i didnt want to make you struggle with collections and such, or at least i wouldnt like you to use them without properly knowing about arrays and loops.

Sign up to request clarification or add additional context in comments.

Comments

1

Assuming you have this array,

studentInfo = ["a","b","c","d","a1","b1","c1","d1", "a2","b2","d2","c2"]

and you want another array like

studentInfoWithA = ["a", "a1", "a2"]

then

    String studentInfo[] = new String[] { "a", "b", "c", "d", "a1", "b1", "c1", "d1", "a2", "b2", "d2", "c2" };

    List<String> newList = new ArrayList<String>();
    for (String info : studentInfo) {
        if (info.startsWith("a")) {
            newList.add(info);
        }
    }

    String[] studentInfoWithA = newList.toArray(new String[0]);

Comments

0

In java 1.8, filtering looks like

String[] result = Arrays.stream(new String[] { "a","b","c","d","a1","b1","c1","d1", "a2","b2","d2","c2" })
    .filter(e -> e.startsWith("a"))
    .toArray(String[]::new);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.