【问题标题】:Print out first part of user specified length打印出用户指定长度的第一部分
【发布时间】:2014-12-02 19:36:06
【问题描述】:

我正在尝试打印用户指定的字母数量。例如用户输入单词-Horse 并指定要打印的字母数- 4. 输出应为Result: Hors。我必须使用子字符串方法。

我的程序删除了用户指定的字母并打印出其余的字母。我怎样才能解决这个问题?

import java.util.Scanner;

public class FirstPart {

public static void main(String[] args) {
    Scanner reader = new Scanner(System.in);
    System.out.println("Type a word: ");
    String word = reader.nextLine();
    System.out.println("Length of the first part: ");
    int firPar = Integer.parseInt(reader.nextLine());

    int i = 0;

    while (i <= firPar) {

        System.out.print("Result: " + word.substring(firPar));
        i++;
        break;
    }

}

}

【问题讨论】:

  • 我建议你阅读 substring 的文档。

标签: java input while-loop


【解决方案1】:

您可能应该使用Scanner.nextInt(),并且您根本不需要循环。只需将String.substring(int, int)0 调用到firPar 就像

public static void main(String[] args) {
    Scanner reader = new Scanner(System.in);
    System.out.println("Type a word: ");
    String word = reader.nextLine();
    System.out.println("Length of the first part: ");
    int firPar = reader.nextInt();
    System.out.println("Result: " + word.substring(0, firPar));
}

【讨论】:

  • 谢谢。那工作得很好。我把事情复杂化了。关于为什么使用 nextInt() 而不是 Integer.parseInt() 的任何原因?
  • @NoahKettler 您已经拥有Scanner,它可以为您完成。我认为它更清洁。
【解决方案2】:
System.out.print("Result: " + word.substring(0, firPar));

如果您只为子字符串指定一个 int,则它是起始索引(包括)。如果您指定 2 个整数,则它是起始索引(包括)结束索引(不包括)。你也可以摆脱你的while循环。

substring(startIndex) //will take startIndex to length

substring(startIndex, endIndex) //will take startIndex (inclusive) to endIndex (exclusive)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-06-17
    • 1970-01-01
    • 2020-04-02
    • 2013-11-18
    • 2016-12-30
    • 1970-01-01
    • 1970-01-01
    • 2021-12-13
    相关资源
    最近更新 更多