-1
if (!pos[1].equals("")) {
    String name = pos[1];
    System.out.println(name);
    int p = 0;
    for (int i = name.length() - 1; i>0; i--){
        if (name.charAt(i)==' ') {
            p = i;  
            break;
        }
        System.out.println(p);
        rank[1] = Integer.parseInt(name.substring(p).trim());
    }
}

In the code, int p is set as i in the if block. However, when it is accessed outside the if block the value still remains 0 and not the value i set in the if condition.

Marouane Gazanayi
  • 5,063
  • 6
  • 39
  • 58
  • 1
    If `p` is supposed to be a variable that exists outside your `if` block, then you shouldn't be declaring it inside the `if` block. – khelwood Feb 10 '17 at 16:03
  • 2
    I'd say the most likely scenario is that the `if` block is not being entered (or it happens to be triggered when `i = 0`. You'll need to give us an example input. Also for future reference, scope issues are very hard to debug with bad formatting like this, it is not easy to tell what is within the `if` block, or the `for` loop for that matter. Edit: it looks like you break out of the loop within the `if` block and if you are only printing `p` after the `if` block, within the loop, it will never print changed. – Justin Hellreich Feb 10 '17 at 16:04
  • Do you get multiple lines with value `0` for a longer name? You're printing `p` for _every_ `i` and also call `Integer.parseInt(...)` which will probably result in an exception (assuming the _first_ character is _not_ a space). What you probably want to do is execute those two lines _after_ the loop and not inside. – Thomas Feb 10 '17 at 16:14

1 Answers1

2

You never print p if it's set to value different than 0.

if(name.charAt(i)==' '){
    p= i;  
    break;
}

If you enter the block you set the value and break out of the loop, so you print value only if you don't enter the block, hence p is still 0.

qwerty1423
  • 295
  • 5
  • 17