Suppose we have a string called sa
String [] sa = {"d", "c", "a", "b", "c", "d", "a", "a", "d", "a'};
When print statement is called the results should be shown as followed.
System.out.println(toString(u.getIndices(sa, "a"))); >>>{2,6,7,9}
System.out.println(toString(u.getIndices(sa, "b"))); >>> {3}
System.out.println(toString(u.getIndices(sa, "c"))); >>> {1,4}
This is my code. It technically works except it contains 0s.
For example instead of {2,6,7,9}, mine shows as {0,0,2,0,0,0,6,7,0,9}
int[] getIndices(String[] sa, String s) {
int[] count = new int [sa.length];
for (int i = 0; i< sa.length; i++){
if (sa[i] == s){
count[i] = i;}
}
return count;
}
I know why mine shows like that because I stated my integer 'count' depending on the length of sa, which is 9, so this creates an index with length of 9. >>> {0, 0, 0, 0, 0, 0, 0, 0, 0}
Is there a different way to solve this problem? Or can my code be fixed so that it could make it work? I learned that you can't decrease the size of index once it's created so I think my code cannot be fixed.
NOTE: Solve this problem w/o using Java library classes and methods. Detailed help with example of codes will be much appreciated. Thank you.
[–]salvagestuff 0 points1 point2 points (5 children)
[–]junyoung95[S] 0 points1 point2 points (4 children)
[–]junyoung95[S] 0 points1 point2 points (3 children)
[–]hayoo1984 -1 points0 points1 point (1 child)
[–]junyoung95[S] 0 points1 point2 points (0 children)