在了解启动索引和子字符串的工作原理时,几乎不需要帮助



这是我的代码

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));
}

结果:

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

启动索引从0开始计数吧?因此结果不应该打印"地狱"吗?

0 = H

1 = e

2 = l

3 = l

substring()的第二个参数是透明度索引。含义:当您输入3时,它将仅给您直到索引2的字母2。

最新更新