0

I have code like this:

here's my code

ans40 must be 2 but in some phones like Samsung s7 shows 3, how can I fix this?

sry for my poor English.

Thanks

dan1st
  • 12,568
  • 8
  • 34
  • 67
Alucard
  • 5
  • 4
  • 1
    Problem may be related to fact that `split` behavior changed in Java 8. More info: [Why in Java 8 split sometimes removes empty strings at start of result array?](https://stackoverflow.com/q/22718744) (use something like `split("?!^")` to get same behavior). But aside from that (1) please don't post text/code as image/link ([more info](https://meta.stackoverflow.com/a/285557)). Use [edit] option to correct your post. (2) Don't call `split("")` many times on same data. Instead store resulting array and reuse it when needed like `String[] arr = str.split(""); //then you can use arr[0], arr[1]`. – Pshemo Apr 17 '21 at 18:41
  • (3) to access all characters in string you don't need to split it at all. Just call `yourString.charAt(index)` like `char ch0 = anskey.charAt(0);`. – Pshemo Apr 17 '21 at 18:42
  • thanks for helping me out, and sry about posting image instead of actual text. appreciate that. – Alucard Apr 18 '21 at 15:11

1 Answers1

0

You can just use the array returned by String#split instead of using lots of variables.

String[] ans=anskey.split("");

Instead of using ans1, you can then just use ans[0].

However, if you want to split for characters, you can also do it like this so you get a char[]:

char[] ans=anskey.toCharArray();

This approach is way more robust as split uses a regex.

And if you nedd to get the values of all variables, you can just iterate over them:

for(int i=0;i<ans.length;i++){
    //Do something with ans[i]
}

or

for(String distinctAns:ans){
    //Do something with ans[i]
}
dan1st
  • 12,568
  • 8
  • 34
  • 67