gpt4 book ai didi

java - 制作正方形网格时我缺少什么?

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

创建一个程序,根据给定的行数和列数生成一组网格框。输入示例:行= 3 列= 4

示例输出:

 -  -  -  -  
| || || || |
- - - -
- - - -
| || || || |
- - - -
- - - -
| || || || |
- - - -

我有这个:

import java.util.Scanner;

public class NewClass {
static Scanner in = new Scanner(System.in);
static int row = 0;
static int col = 0;

String[] square = { " -" + //"\n" + "| |" + //"\n" + " -" //"\n" };

public static void main(String[] args) {
NewClass nc = new NewClass();

System.out.println("row:");
row = in.nextInt();
System.out.print("column:");
col = in.nextInt();

for (int i = 0; i < row; i++) {
nc.column(col);
System.out.println();
}
}

public void column(int col) {
for (int j = 0; j < col; j++) {
System.out.print(square[0]);
}
}
}

但是输出不正确。我错过了什么?

最佳答案

您可以使用两个嵌套的 for 循环来完成此操作。内部 for 循环打印列,外部 for 循环打印换行符以开始新行。

public static void main(String[] args)  {
Scanner in = new Scanner(System.in);
int row = 0, col = 0;
System.out.println("row:"); row = in.nextInt(); System.out.print("column:"); col = in.nextInt();

for (int i = 0; i < row; i++) {
for (int j = 0; j < col; j++) {
System.out.print(" - ");
}
System.out.print("\n");
for (int j = 0; j < col; j++) {
System.out.print("| |");
}
System.out.print("\n");
for (int j = 0; j < col; j++) {
System.out.print(" - ");
}
System.out.print("\n");
}
}

输入:行=3 列=4

输出:

 -  -  -  - 
| || || || |
- - - -
- - - -
| || || || |
- - - -
- - - -
| || || || |
- - - -

关于java - 制作正方形网格时我缺少什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21107402/

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