1

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

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”,我当前的程序给了我

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

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

现在我正在尝试获取输出

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

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

4

1 回答 1

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();

    }
    }
于 2016-02-27T04:20:44.797 回答