Java - 如何将两个相似的for循环变成一个循环

标签 java loops for-loop

我有两个类似的循环,我被要求消除其中一个,但我不知道如何......

这是我的代码:

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/

相关文章:

python - 尝试计算 .txt 文件中的点之间的距离

c# - 什么时候处理对象? C#

php - foreach 循环中 current() 的意外行为

java - toString() 不适用于父类(super class)和子类

java - java中的ArrayList错误(无法使两个数字相等)

java - 我有一个包含多个 JSON 对象的数据字符串,如何将字符串中的所有 JSON 对象存储在填充对象的数组中?

java - 金钱累积按钮

c# - 获取数组索引的优雅方式

Java:网络在重置时断开连接

java - 在 Java 中使用 Thread.interrupt 终止线程