0

I'm trying to print the first char in one line, then the first two chars in the next line etc. of a string.

I do not understand the reason for a blank line in the beginning and why the last line did not complete the word. I was able to get the desired output by a change in for loop to (i=1 and i<=k).

public class Tester6 {
    public  static void main(String[] args) {
    Scanner input = new Scanner(System.in);
    String userInput = input.nextLine();
    int k = userInput.length();
    for(int i = 0; i < k; i++) {
        System.out.println(userInput.substring(0,i));
    }
  }
}

The output for the input four is,

f
fo
fou

kiran
  • 25
  • 7
  • Index start from 0. First time in loop, It will print empty string as you are printing string which start from 0 to 0 ("from" and "to" both are zero.). In last iteration, you will not have last char as you are put length as index value. Length and index two diff thing; but are connected to each other. – Vijay Aug 18 '19 at 18:55

1 Answers1

3

Because the substring (0,0) is "". As the String.substring(int, int) Javadoc says (in part)

The substring begins at the specified beginIndex and extends to the character at index endIndex - 1.

That is why you get a blank line with i at 0. And why you don't get the last character when i is at the last character. You could adjust your call to substring with + 1 like

for (int i = 0; i < k; i++) {
    System.out.println(userInput.substring(0,i + 1));
}
Elliott Frisch
  • 198,278
  • 20
  • 158
  • 249
  • So `substring(0, 0)` would start at index 0 (zero) and extend to index -1 (minus one), wouldn't it? – Abra Aug 18 '19 at 18:19
  • No. Because it **extends** to `endIndex - 1` - which means it returns the characters between `0` and `0`. Which is `""`. – Elliott Frisch Aug 18 '19 at 19:37