gpt4 book ai didi

java - 重新排列代码以获得所需的方 block 输出?

转载 作者:太空宇宙 更新时间:2023-11-04 12:52:45 30 4
gpt4 key购买 nike

我根据用户输入创建了两个正方形,一个是实心正方形,一个是空心正方形。按照我的教授的建议,我将其设置为先打印一个,然后打印另一个,但是我现在需要它们在同一行上打印。如何重新排列我的代码,使它们彼此并排打印而不是彼此重叠?

import java.util.Scanner;
public class javaapplication30 {


public static void main(String[] args) {
Scanner in = new Scanner(System.in);

int side = 0;
System.out.printf("This program will display a full and an empty square given the side length.\n");
System.out.print("Enter a side length: ");
side = in.nextInt();

//Filled square

for (int i=1; i <=side; i++) {
for (int j=1; j <= side; j++) {
System.out.printf("*");
}
System.out.println();
}

System.out.println();

//Hollow square
for (int i=1; i <=side; i++) { //first row
System.out.printf("*");
}
System.out.println();

for (int j=1; j <= side-2; j++) {
for (int i=1; i <= side; i++) { //middle rows
if (i == 1 || i == side) {
System.out.printf("*");
}
else {
System.out.print(" ");
}
}
System.out.println();
}


for (int i=1; i <=side; i++) { //last row
System.out.printf("*");
}
System.out.println();



}
}

举个例子,如果我输入当前程序给出的整数“5”

*****
*****
*****
*****
*****

*****
* *
* *
* *
*****

现在我正在尝试获取输出

***** *****
***** * *
***** * *
***** * *
***** *****

非常感谢任何帮助,谢谢。

最佳答案

Totally Working code. You may Compile and Run it . I made it successfully Thank You.

import java.util.Scanner;
class javaapplication30 {

public static void main(String[] args) {
Scanner in = new Scanner(System.in);

int side = 0;
System.out.printf("This program will display a full and an empty square given the side length.\n");
System.out.print("Enter a side length: ");
side = in.nextInt();
System.out.println();
//Filled square
int row = (side * 2)+1;
for (int i=1; i <=side; i++) {
for (int j=1; j <= row; j++) {
if(j==side +1){
System.out.print(" ");
continue;
}if(((j>side+2) && (i >1 && i< side) && (j<row))){
System.out.print(" ");
continue;
}else{
System.out.print("*");
}
}
System.out.println();
}

System.out.println();

}
}

关于java - 重新排列代码以获得所需的方 block 输出?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35665399/

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