简体   繁体   English

我如何在Java中使用for循环打印此模式*** +++ ------ +++ ***?

[英]how can i print this pattern***+++------+++*** using for loop in java?

I used this code for the 1st part of the code: 我将此代码用作代码的第一部分:

for(int i=0;i<2;i++)
  for(int j=0; j<3; j++)
    System.out.print("*");  

  for(int j=0; j<3; j++)
    System.out.print("+");

  for(int j=0; j<3; j++)
    System.out.print("-"); 
}

Output: 输出:

***+++---

There can be many ways to do it. 有很多方法可以做到这一点。 One of the ways is as follows: 方式之一如下:

public class Main {
    public static void main(String args[]) {
        char[] patternChars = { '*', '+', '-' };
        int repeat = 3;
        for (int i = 0; i < patternChars.length * 2; i++) {
            if (i < patternChars.length) {
                printChars(patternChars[i], repeat);
            } else {
                printChars(patternChars[patternChars.length * 2 - i - 1], repeat);
            }
        }
    }

    static void printChars(char ch, int repeat) {
        for (int i = 1; i <= repeat; i++) {
            System.out.print(ch);
        }
    }
}

Output: 输出:

***+++------+++***

The main feature of this solution is, if you add more characters to the char array, it will work without changing anything else eg the output for char[] patternChars = { '*', '+', '-','$' }; 此解决方案的主要功能是,如果您向char数组添加更多字符,它将在不更改其他任何内容的情况下运行,例如char[] patternChars = { '*', '+', '-','$' }; will be as follows: 将如下所示:

***+++---$$$$$$---+++***

Your pattern consists of three distinct characters repeated three times in an ascending / descending order. 模式由三个不同的字符组成,这些字符以升序/降序重复三次。 I would simplify the problem, place each character into an array and iterate the array printing each element three times. 我将简化问题,将每个字符放入一个数组中,并对该数组进行迭代,将每个元素打印三遍。 Like, 喜欢,

char[] arr = { '*', '+', '-', '-', '+', '*' };
for (char ch : arr) {
    System.out.print(ch);
    System.out.print(ch);
    System.out.print(ch);
}
System.out.println();

Outputs (as requested) 输出(根据要求)

***+++------+++***

Or, just iterate the characters in your desired output. 或者,仅迭代所需输出中的字符。 Like, 喜欢,

String s = "***+++------+++***";
for (int i = 0; i < s.length(); i++) {
    System.out.print(s.charAt(i));
}
System.out.println();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM