gpt4 book ai didi

java - java中另一个字符的正方形内的字符正方形

转载 作者:行者123 更新时间:2023-12-02 04:19:50 24 4
gpt4 key购买 nike

我想根据行数以这种格式打印一个字符方 block 例如:

    number of lines : 4 
output :

a a a a
a b b a
a b b a
a a a a

number of lines : 5

output :

a a a a a

a b b b a

a b c b a

a b b b a

a a a a a

但我不知道如何得到这样的结果,这是我的代码

import java.util.Scanner;
public class test {
public static void main ( String arugs [] ) {
Scanner read= new Scanner(System.in) ;
System.out.println ( " please inter the number of line : " ) ;
int size = read.nextInt();
int []array = new int[size ];
int c = 97;

for(int i = 0; i < size; ++i) {

for(int j = 0; j < size; ++j){
array[i]= c;
System.out.print( (char)array [i]);}

System.out.println();

}
}
}
}

最佳答案

一个有趣的方法:

public static void main(String arugs[]) {
Scanner sc = new Scanner(System.in);
System.out.println("Please enter the number of lines : ");
int size = sc.nextInt();
sc.close();

for (int i = 0; i < size; i++) {
for (int j = 0; j < size; j++) {
System.out.print((char) ('a' + Math.min(size - j - 1, Math.min(size - i - 1, Math.min(i, j)))) + " ");
}
System.out.println();
}
}

想法:

  • 我们需要计算特定点(i, j)的“深度”。该单元格的值将为'a' + 深度
  • 深度定义为点到矩阵任意边的最小距离

关于java - java中另一个字符的正方形内的字符正方形,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32917098/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com