猿问

打印字符串模式的Java程序

如果输入字符串是“ADMINISTRATIONS”,则模式应该是这样的 A DM INI STRA TIONS


最后一行应该完全填满


如果输入字符串是“COMPUTER”,则模式应该是这样的 COM PUT ER**


不完整的最后一行应该用 * 填充


我有图案,但无法打印星星。


    int k=0;

    String str = "computer";

    String[] s=str.split("\\B");

    for(int i=0; i<s.length;i++){

        for(int j=0; j<i;j++){

            if(k<s.length){

        System.out.println(s[k]);

        k++;

            }

    }

        System.out.println();

帮我解决这个问题。


LEATH
浏览 204回答 2
2回答

梵蒂冈之花

在没有提供代码时编写 - 早些时候它被标记为C。以问题陈述中描述的方式打印字符串是简单的递归。这是执行此操作的C等效代码(因为此问题也已在Java 中标记):&nbsp; #include<stdio.h>&nbsp; int i=1;&nbsp; void fun(char c[])&nbsp; {&nbsp; &nbsp; &nbsp; int j=0;&nbsp; &nbsp; &nbsp; while((j<i)&&(c[j]))&nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; printf("%c",c[j++]);&nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; while((c[j]=='\0')&&(j<i))&nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; printf("*");&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; ++j;&nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; ++i;&nbsp; &nbsp; &nbsp; if(c[j])&nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; printf(" ");&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; fun(c+j);&nbsp; &nbsp; &nbsp; }&nbsp; }&nbsp; int main(void)&nbsp; {&nbsp; &nbsp; &nbsp; char c[]="computer";&nbsp; &nbsp; &nbsp; fun(c);&nbsp; &nbsp; &nbsp; return 0;&nbsp; }输出:&nbsp;c om put er**如果要替换\0检查,则可以使用字符串的长度作为检查,因为我不知道 Java 中是否存在空终止。

ITMISS

Java 版本,因为注释不适用于代码:String str = "computer";int k = 0;for (int i=0; k<str.length(); i++) {&nbsp; // note: condition using k&nbsp; &nbsp; for (int j=0; j<i; j++) {&nbsp; &nbsp; &nbsp; &nbsp; if (k < str.length()) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; System.out.print(str.charAt(k++));&nbsp; &nbsp; &nbsp; &nbsp; } else {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; System.out.print("*");&nbsp; // after the end of the array&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }&nbsp; &nbsp; System.out.println();}未经测试,只是一个想法注意:没有必要使用,split因为我们想要字符串的每个字符 - 我们可以使用charAt(或toCharArray)。使用print而不是println不改变行。
随时随地看视频慕课网APP

相关分类

Java
我要回答