here, it gives b's element as null rather than storing array a's value. Basically, I can't go inside the if statement
public class Dil {
public static void main(String[] args) {
String s = "is2 sentence4 This1 a3";
String a[]=s.split(" ");
String b[]=new String[a.length];
System.out.println(Arrays.toString(a));
for(int i=1;i<a.length;i ){
for(int j=0;j<a.length-1;j ){
if(a[j].charAt(a[j].length()-1)==i){
b[i-1]=a[j];
break;
}
}
}
System.out.println(Arrays.toString(b));
}
}
CodePudding user response:
I think thats more like what u wanted:
public class Dil {
public static void main(String[] args) {
String s = "is2 sentence4 This1 a3";
String a[]=s.split(" ");
String b[]=new String[a.length];
System.out.println(Arrays.toString(a));
for(int i=1;i<a.length;i ){
for(int j=0;j<a.length-1;j ){
if(a[j].charAt(a[j].length()-1)==((char)(i '0'))){
b[i-1]=a[j];
break;
}
}
}
System.out.println(Arrays.toString(b));
}
}
But that just works if 0<=i<=9
CodePudding user response:
You have two unrelated problems.
here, it gives b's element as null rather than storing array a's value.
That's because your instantiating a new and empty array, only providing to it the size of array a (not the values!), with:
String b[] = new String[a.length];
If you want to copy an array, better do:
String[] a = new String[] {/*..your array..*/};
String[] b = new String[a.length];
System.arraycopy(a, 0, b, 0, a.length);
or
String[] b = Arrays.copyOf(a, a.length);
Basically, I can't go inside the if statement
Variable of type char, indeed can store a number, as under the hood, chars are represented as ASCII codes.
Therefore, your:
(a[j].charAt(a[j].length()-1)==i)
would only evaluate to true, when i will be equal to ASCII code of the char in question; however, characters represented with [0; 31] codes, are non-printable ones, which, most likely, will not be include in your strings and hence - your if's condition will not evaluate to true.
