通过接受字符串使用for循环打印模式(printing a pattern using for loop by accepting a string)

系统教程 行业动态 更新时间:2024-06-14 17:00:14
通过接受字符串使用for循环打印模式(printing a pattern using for loop by accepting a string)

示例输入字符串:

BlueJ的

输出:

b***b *l*l* **u** *e*e* j***j

(其中'*'表示空格)

到目前为止我做了这么多:

int n = s.length() - 1; int i, j; for (i = 0; i <= n; i++) { for (j = 0; j <= (n + 1); j++) { if (i == j || i == n - (j - 1)) System.out.print(s.charAt(i)); else { System.out.print("*"); } } System.out.println(); }

但输出是:

b****b *l**l* **uu** **ee** *j**j*

Sample input string:

bluej

Output:

b***b *l*l* **u** *e*e* j***j

(where '*' indicates a blank space)

I have done this much so far:

int n = s.length() - 1; int i, j; for (i = 0; i <= n; i++) { for (j = 0; j <= (n + 1); j++) { if (i == j || i == n - (j - 1)) System.out.print(s.charAt(i)); else { System.out.print("*"); } } System.out.println(); }

But output is:

b****b *l**l* **uu** **ee** *j**j*

最满意答案

只需将i == n-(j-1)替换为i == n - j ,将第二个替换for (j = 0; j <= n+1; j++)循环for (j = 0; j <= n; j++) :

int n = s.length() - 1; int i, j; for (i = 0; i <= n; i++) { for (j = 0; j <= n; j++) { if (i == j || i == n - j) System.out.print(s.charAt(i)); else { System.out.print("*"); } } System.out.println(); }

Just replace i == n-(j-1) with i == n - j and second for loops for (j = 0; j <= n+1; j++) to for (j = 0; j <= n; j++) :

int n = s.length() - 1; int i, j; for (i = 0; i <= n; i++) { for (j = 0; j <= n; j++) { if (i == j || i == n - j) System.out.print(s.charAt(i)); else { System.out.print("*"); } } System.out.println(); }

更多推荐

本文发布于:2023-04-18 00:59:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/dzcp/9a73abc9bbfc905e917303f337adfc0e.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:字符串   模式   printing   pattern   accepting

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!