我根据用户输入创建了两个正方形,因此一个是填充的正方形,一个是空心正方形。根据我的教授的建议,我将它设置为打印一个然后打印另一个,但我现在需要它们在同一行上打印。如何重新排列我的代码,使它们彼此相邻而不是彼此重叠?
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',我当前的程序会给我
*****
*****
*****
*****
*****
*****
* *
* *
* *
*****
现在我正在尝试获取输出
***** *****
***** * *
***** * *
***** * *
***** *****
非常感谢任何帮助,谢谢。
答案 0 :(得分:0)
完全正常工作的代码。您可以编译并运行它。我成功了谢谢你。
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();
}
}