作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我正在尝试用 java 编写一个程序,该程序将为输入的字符串提供一个模式,如下所示
C O M P U T E R
O E
M T
P U
U P
T M
E O
R E T U P M O C
这是我的程序代码
import java.util.Scanner;
class pandapattern
{
public static void main(String args[])
{
Scanner sc=new Scanner(System.in);
System.out.print("Enter a word : ");
String s=sc.nextLine();
System.out.println();
int l=s.length();
for(int i=0;i<+l;i++)
{
System.out.print(s.charAt(i)+" ");
}
char[][] frwd = new char[l][1];
char[][] bcwd = new char[l][1];
for(int f=1;f<l;f++)
{
frwd[f][0]=s.charAt(f);
}
for(int b=l-2;b>=0;b--)
{
bcwd[b][0]=s.charAt(b);
}
for(int p=1;p<l;p++)
{
System.out.print("\n"+frwd[p][0]);
}
for(int p1=l-1;p1>=0;p1--)
{
System.out.print(bcwd[p1][0]+" ");
}
}
}
我得到了这个模式:
C O M P U T E R
O
M
P
U
T
E
R E T U P M O C
如何打印整个图案?
请帮我解决一下。
最佳答案
您只需要一个 char[]
数组,而不需要更多。诀窍是解决问题“逐行”。
见下文:
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter word for Panda Pattern: ");
String word = scanner.nextLine();
String wspace = " ";
//convert user input from String to char[]
char[] wordLetters = word.toCharArray();
//define array's length, for ease of reference
int length = wordLetters.length;
//initially print the sentence in a horizontal line
for (char wordLetter : wordLetters) {
System.out.print(wordLetter + wspace);
}
//insert new line to start printing for the pattern
System.out.print("\n");
/*A for loop that will print the left-most letters vertically
We start the loop from 1, because the first letter was already printed*/
for(int i=1; i<length; i++){
System.out.print(wordLetters[i]);
/*now we have an inner loop that will print the spaces and the
rest of the letters in reverse order*/
for(int j=1; j<length; j++){
//conditional for IF we are at final line
if(i == length-1 && j != length-1)
System.out.print(wspace + wordLetters[i-j]);
//conditional for printing right-most letters
else if(j == length-1) {
System.out.print(wspace + wordLetters[j-i]+"\n");
}
//THIS WILL PRINT 2 WHITE-SPACES.
else
System.out.print(wspace + wspace);
}
}
}
Why didn't I need a second array ?
由于这种模式只需要一个单词,因此反向打印意味着仍然有相同数量的字母需要处理,因此任何其他数组都将具有相同的长度。
因此,我们可以完全省略创建新数组!
为什么不利用for循环
和数组
给我们带来的力量呢?
关于java - 如何在 Java 中打印此模式中的不同字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54276529/
我是一名优秀的程序员,十分优秀!