有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java如何在每次使用嵌套循环打印字符串时取出最后一个字符

所以我刚在我的课堂上学习了嵌套循环,我们得到了一个程序,但我似乎无法理解。程序提示用户输入一个单词,输出结果应打印出该单词在不同行中的字母数的多少倍,并且每次打印该单词时应删除该单词的最后一个字符

这就是我现在得到的。我只能让它打印出整个单词以及应该打印多少次

import java.util.*;
public class MyClass {
    public static void main(String args[]) {
        Scanner kbreader = new Scanner (System.in);

        System.out.print("Enter a word: ");
        String word = kbreader.nextLine();


        for ( int k = word.length(); k > 0; k--)
        {

            for (int m = 0; m <= word.length()-1; m++)
            {
                System.out.print(word.charAt(m));
            }

            System.out.println();          
        }       
    }
}

程序应打印如下内容:

输入一个单词:hello

hello

hell

hel

he

h

但我的程序会打印出以下内容:

hello

hello

hello

hello


共 (3) 个答案

  1. # 1 楼答案

    您可以尝试:

    int length = word.length();
    IntStream.range(0, length).forEach(i -> System.out.println(word.substring(0, length - i)));
    

    IntStream.range(0, length).mapToObj(i -> word.substring(0, length - i)).forEach(System.out::println);
    

    它使用java stream并且非常简洁

  2. # 2 楼答案

    子字符串函数就是您要查找的。它存在于(可能)每种编程语言中

    下面是一个工作示例:https://www.w3schools.com/jsref/jsref_substring.asp

    同样重要的是,如果参数使用负数,它将从字符串的“结尾”而不是前面开始子字符串,或者它将向后计数而不是向前计数

    你的循环中有一个计数器,所以你应该能够轻松地玩一个游戏,并让它与这个函数一起工作

  3. # 3 楼答案

    你只是犯了一个小错误。您可能会注意到,您没有将k用于任何事情,因此您只执行了相同的任务k次。只需将m <= word.length()-1更改为m < word.length()-k

    import java.util.*;
    
    public class MyClass {
    public static void main(String args[]) {
    
        Scanner kbreader = new Scanner (System.in);
    
        System.out.print("Enter a word: ");
        String word = kbreader.nextLine();
    
    
        for ( int k = word.length(); k > 0; k )
        {
    
            for (int m = 0; m < word.length()-k; m++)
            {
                System.out.print(word.charAt(m));
            }
    
            System.out.println();          
           }       
       }
     }