-3

Here is my code

public static void main(String[] args) {
    Scanner reader = new Scanner(System.in);

    System.out.print("Type a word: ");
    String userWord = reader.nextLine();

    System.out.print("Length of the first part: ");
    int userLength = Integer.parseInt(reader.nextLine());

    System.out.println("Result: " + userWord.substring(0, userLength));
}

Result:

Type a word: hellothere
Length of the first part: 3
Result: hel

Starting index starts counting from 0 right? So shouldn't the result print "hell"?

0 = h

1 = e

2 = l

3 = l

1 Answers1

0

The second parameter of substring() is an exlusive index. Means: When you enter 3 it will give you only the letters until index 2. This isn't one of the most obvious methods in the Java API, but should be well documented.

Florian S.
  • 386
  • 1
  • 12