2016-02-27 25 views
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」我目前的計劃讓我

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

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

現在我試圖讓輸出

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

任何幫助是很大的感謝,謝謝。

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

    } 
    }