英文:
Pattern printing problem in java: “frame" composed out of the symbols ‘.’ and ‘*’, dimensions AxB
问题
Here's the translated code for the second task:
static void second(int a, int b) {
for (int i = 1; i <= a * b; i++) {
for (int j = 1; j <= a; j++) {
for (int k = 1; k <= b; k++) {
if (j == 1 || j == a || k == 1 || k == b) {
System.out.print("*");
} else {
System.out.print(".");
}
}
System.out.print(" ");
}
System.out.println();
}
}
This code will generate the desired pattern for the given values of "a" and "b" in the second task.
英文:
Write a program that reads natural numbers a and b and prints a “frame” composed of the symbols ‘.’ and ‘*’ dimensions axb as below (dots are inside and stars around the dots):
a=4,b=4; a=3,b=1
**** *
*..* *
*..* *
****
I solved it this way:
static void first(int a, int b) {
for(int i=1; i<=a; i++) {
for(int j=1; j<=b;j++) {
if (i==1 || i==a || j==1 || j==b)
System.out.print("*");
else System.out.print(".");
}
System.out.println();
}
}
The next task is a bit different, here is what a program should return for given a and b:
a=3,b=1
****
*..*
*..*
****
*..*
*..*
****
*..*
*..*
****
a=4,b=4
*************
*..*..*..*..*
*..*..*..*..*
*************
*..*..*..*..*
*..*..*..*..*
*************
*..*..*..*..*
*..*..*..*..*
*************
*..*..*..*..*
*..*..*..*..*
*************
I do not know how to do this one, when I tried using the first method as a help method I just get a messy pattern..
答案1
得分: 2
如果你考虑一下,*
总是用于第 3*i
个元素,其中 i
的范围从 0
到 a*3
。对于列也是类似的:它总是用于第 3*j
个元素,其中 j
的范围从 0
到 b*j
。所有其他元素都是 .
。
你可以通过使用模运算 (%
) 来简单地表示这个结构:
class Main {
static void print(int a, int b) {
for (int row = 0; row <= a*3; row++) {
for (int col = 0; col <= b*3; col++) {
if (row % 3 == 0) {
System.out.print("*");
}
else if (col % 3 == 0) {
System.out.print("*");
}
else {
System.out.print(".");
}
}
System.out.print("\n");
}
}
public static void main(String args[]) {
print(3, 1);
print(4, 4);
}
}
英文:
If you think about it, a *
is always used for the 3*i
th element in a row where i
ranges from 0
to a*3
. It's similar for the columns: it's always the 3*j
th element in a col where j
ranges from 0
to b*j
. All other elements are .
s.
You can express this structure simply by using the modulo operation (%
):
class Main {
static void print(int a, int b) {
for (int row = 0; row <= a*3; row++) {
for (int col = 0; col <= b*3; col++) {
if (row % 3 == 0) {
System.out.print("*");
}
else if (col % 3 == 0) {
System.out.print("*");
}
else {
System.out.print(".");
}
}
System.out.print("\n");
}
}
public static void main(String args[]) {
print(3, 1);
print(4, 4);
}
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论