java - 打印出用户指定长度的第一部分

标签 java input while-loop

我正在尝试打印出用户指定的字母数量。例如用户输入单词“Horse”并指定他们想要打印的字母数量- 4. 输出应为“结果: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;
    }

}

}

最佳答案

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

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

关于java - 打印出用户指定长度的第一部分,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27257495/

相关文章:

java - Android - Kotlin Serializable 与 Java Serializable,性能是否相同?

c++ - 从文件 (ifstream) 读取并写入文件 (ofstream) - 编码问题

c - 关于C中的文件输入和输出

java - 在 while 循环中使用扫描仪时,如何 "prime"循环并创建哨兵?

swift - 等待 boolean 值成为 'true' 的更优雅的方式

c - 如何使用 while 循环

java - Spigot Minecraft 插件编码 NoClassDefFound 错误 mysql

java - 软件开发中模型和图表之间的概念区别是什么

python - While 循环与用户输入和命令一起运行

Java+Eclipse : how do you debug a java program that is receiving piped/redirected stdin?