我有两个类似的循环,我被要求消除其中一个,但我不知道如何......
这是我的代码:
import java.util.Scanner;
public class Tree {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter height: ");
int tmp = input.nextInt();
int x = (tmp-1)*2+1;
int y = x/2;
int z = 1;
for(int i=0; i<tmp; i++){
for(int j=0; j<=y; j++){
System.out.print(" ");
}
for(int k=0; k<z; k++){
System.out.print("*");
}
System.out.println();
y--;
z+=2;
}
for(int i=0; i<tmp; i++){
y++;
for(int j=0; j<=y; j++){
System.out.print(" ");
}
z-=2;
for(int k=0; k<z; k++){
System.out.print("*");
}
System.out.println();
}
}
}
我应该编写一个方法并调用它吗?
我已经挣扎了好几天了..
希望得到一个简单的建议,因为我只是初学者。
非常感谢您的帮助。谢谢!
最佳答案
我认为应该从更高的层面来考虑这个问题:
您想要的(基于您的代码)是表示钻石的 *
和 的二维矩阵,所以让我们尝试找到一个包含两个的解决方案循环,对应于矩阵/屏幕的两个维度,用一些条件来定义每个“像素”的渲染:
// vertical dimension (i:= line index)
for (int i =0; i< 2* tmp +1 ; ++i){
if(i!=tmp){ //handling of middle-line corner case
// horizontal dimension (j:= row index)
for (int j=0; j< 2*tmp ; ++j){
if (condition(tmp, i,j)){
System.out.print("*");
}else{
System.out.print(" ");
}
}
if(i!=2 * tmp) { // handling of last line corner case
System.out.println();
}
}
}
private boolean condition(int tmp, int i, int j) {
// return true if and only if the (i, j) pixel is within the central diamond
return Math.abs(tmp-i) + Math.abs(tmp-j) <= tmp;
}
对极端情况的两种处理只是为了匹配您的结果。
关于Java - 如何将两个相似的for循环变成一个循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37281145/