我想创建一个看起来像盒子的图案。
我尝试了每一个反射和镜子,但无法实现精确的循环。
它的盒子看起来像循环String s="ROHIT";
这可以满足您的要求(想法是检查您的内部级别):
public static void main(String[] args) {
String s = "ROHIT";
int size = s.length() * 2;
for (int i = 0; i < size; i++) {
for (int j = 0; j < size; j++) {
if ((j > i && size - j > i) || (size - j > size - i && j >= size - i)) {
print(s, i);
} else {
print(s, j);
}
}
System.out.println("");
}
}
private static void print(String s, int i) {
if (i < s.length()) {
System.out.print(s.charAt(i));
} else {
System.out.print(s.charAt(s.length() - i % s.length() - 1));
}
}
实际上,这更直观:
public static void main(String[] args) {
String s = "ROHIT";
int size = s.length() * 2;
int max = s.length();
for (int i = 0; i < size; i++) {
for (int j = 0; j < size; j++) {
int level = Math.min(normalize(i, max), normalize(j, max));
System.out.print(s.charAt(level));
}
System.out.println("");
}
}
private static int normalize(int i, int max) {
return (i >= max) ? 2 * max - i - 1: i;
}
int n = 2 * word.length();
for (int i = 0; i < n; ++i) {
int iWord = i < word.length()? i : 2 * word.length() - 1 - i;
for (int j = 0; j < n; ++j) {
int jWord = j < word.length()? j : 2 * word.length() - 1 - j;
int diagonal = Math.min(iWord, jWord);
System.out.print(word.charAt(diagonal));
}
System.out.println();
}
这是算法/伪代码
for(each row)
{
if(firstrow) print total row;
else if(lastrow) print total row;
else {
for (each column)
{
if(firstcol) print col;
if(lastcol) print col;
}
}
}