挂信计划.

这几天在练习JAVA的问题,遇到了这样的问题:


I/p: I Am A Good Boy


O/p:


I A A G B

  m   o o

      o y

      d

这是我的代码。


System.out.print("Enter sentence: ");

String s = sc.nextLine();

s+=" ";

String s1="";

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

{

    char c = s.charAt(i);

    if(c!=32)

    {s1+=c;}

    else

    {

        for(int j=0;j<s1.length();j++)

        {System.out.println(s1.charAt(j));}

        s1="";

    }

}

问题是我无法进行此设计。我的输出是每行中的每个字符。


FFIVE
浏览 81回答 1
1回答

神不在的星期二

首先,您需要用空格作为分隔符来划分字符串并将它们存储在字符串数组中,您可以通过编写自己的代码将一个字符串划分为多个字符串来完成此操作,或者您可以使用名为的内置函数split()将字符串“拆分”为字符串数组后,只需迭代字符串数组,次数与最长字符串出现的次数相同,因为这是您要打印的最后一行(从共享输出中可以理解),即,d来自 string Good,因此迭代字符串数组,直到打印最大/最长字符串中的最后一个字符,然后从那里退出。您需要在迭代字符串数组时处理任何边缘情况,例如没有任何额外字符可供打印的字符串,但需要为下一个具有输出顺序字符的字符串打印空格。以下是您可以参考的代码段,但请记住在进一步阅读之前尝试上面解释的逻辑,import java.io.*;import java.util.*;public class MyClass {&nbsp; &nbsp; public static void main(String args[]) throws IOException{&nbsp; &nbsp; &nbsp; &nbsp; //BufferedReader br = new BufferedReader(new InputStreamReader(System.in));&nbsp; &nbsp; &nbsp; &nbsp; Scanner sc = new Scanner(System.in);&nbsp; &nbsp; &nbsp; &nbsp; String[] s = sc.nextLine().split(" ");&nbsp; &nbsp; &nbsp; &nbsp; // Split is a String function that uses regular function to split a string,&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; // apparently you can strings like a space given above, the regular expression&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; // for space is \\s or \\s+ for multiple spaces&nbsp; &nbsp; &nbsp; &nbsp; int max = 0;&nbsp; &nbsp; &nbsp; &nbsp; for(int i=0;i<s.length;i++) max = Math.max(max,s[i].length()); // Finds the string having maximum length&nbsp; &nbsp; &nbsp; &nbsp; int count = 0;&nbsp; &nbsp; &nbsp; &nbsp; while(count<max){ // iterate till the longest string exhausts&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; for(int i=0;i<s.length;i++){&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; if(count<s[i].length()) System.out.print(s[i].charAt(count)+" "); // exists print the character&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; else System.out.print("&nbsp; "); // Two spaces otherwise&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; System.out.println();count++;&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }}编辑:我正在分享下面的字符串输出This is a test InputT i a t I&nbsp;h s&nbsp; &nbsp;e n&nbsp;i&nbsp; &nbsp; &nbsp;s p&nbsp;s&nbsp; &nbsp; &nbsp;t u&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; t&nbsp; &nbsp;
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java