2013-11-28 174 views
0

我在面試時被問及以下問題。我被要求使用*角色進行「填充打印」的形式。下面是我爲我的回答(在Java中)提供的代碼:有沒有更好的方式來做到這一點比我的方式?

編輯:

是這樣的:用戶輸入3:

x x x x x 
x * * * x 
x * * * x 
x * * * x 
x x x x x> 


public class asterisk { 

    public static void main (String args[]){ 
     int input,ast; 
     Scanner scan = new Scanner(System.in); 

     System.out.println("Enter number: "); 
     input = scan.nextInt(); 


     if(input>0) { 
      topBottom(input); 
      for(int x=1; x<=input; x++){ 
       System.out.print("x "); 
       for(ast=1; ast<=input; ast++) { 
        System.out.print("* "); 

       } 
       System.out.print("x "); 
       System.out.println(); 
      } 
      topBottom(input); 
     } else { 
      System.out.print("x "); 
     }  
    } 

    public static void topBottom(int input) {   
     for(int top = 1; top<=input+2; top++) { 
      System.out.print("x "); 
     } 
     System.out.println(); 
    } 

}

有沒有更好的更有效除了我的方式之外這麼做嗎?此外,我在代碼中做得不好?

這對我來說真的很重要。我現在正在練習常見的面試編碼問題。

+1

http://codereview.stackexchange.com/這個練習的 –

+1

的目標不是讓你編寫一個「高效」的算法。這只是爲了看看你是否理解循環。儘量使其可讀性,使用簡短的命名方法,使其在間距中保持一致,以便正確縮進代碼。而且,循環傳統上從Java開始爲0。變量在最後一刻聲明和初始化,範圍最窄。 –

+2

初學者:public final static String CROSS =「x」; public final static String STAR =「*」; - 然後使用System.print(STAR);或CROSS –

回答

1

您的代碼很好,但有一些建議。 按照慣例,方法應該以動詞開頭。使用topBottom函數是有問題的。我發現它使代碼比任何東西都更容易混淆。考慮可讀性和效率。

這樣的方法更容易閱讀,並且不包含額外的方法。

對於N + 2行N + 2個字符

for(int i=0; i<input+2; i++) { 
    for(int j=0; j<input+2; j++) { 

始終打印X用於第一行和最後一行

if(i == 0 || i == input+1) { 
     System.out.print("X "); 
    } 

對於所有其他的行打印X對於第一和最後一個字符,否則打印*

else { 
     if(j == 0 || j == input+1) { 
     System.out.print("X "); 
     } else { 
     System.out.print("* "); 
     } 
    } 

最終結果:

for(int i=0; i<input+2; i++) { 
    for(int j=0; j<input+2; j++) { 
    if(i == 0 || i == input+1) { 
     System.out.print("X "); 
    } else { 
     if(j == 0 || j == input+1) { 
     System.out.print("X "); 
     } else { 
     System.out.print("* "); 
     } 
    } 
    } 
    System.out.println(); 
} 
+0

嗯,這看起來很有趣。看起來有點不同於我的答案,但我看到的邏輯,我會嘗試和研究這一個以及。非常感謝@Jordonias –

+0

很好的解釋。此外,你可以摺疊2個IF爲一個: if((i == 0 || i == input + 1)||(j == 0 || j == input + 1)) – Pankaj

0

小的變化,@邁克爾代碼,以打印下一行並打印內環內的焦炭

 // y = column 
     for(int y=0; y < input; y++){  
     // x = row 
     for(int x=0; x< input; x++){ 
      nextChar = (x == 0 || y == 0 || (x+1) == input 
      || (y+1) == input) ? BORDER : FILLING; 
      System.out.print(nextChar); 
     } 
     System.out.println(); 
     } 
+0

謝謝,看起來更好 –

+0

可以省略System.out.println();通過將nextChar行更改爲:nextChar =(x == 0 || y == 0)? BORDER:((x + 1)== input ||(y + 1)== input)? BORDER。「\ n」:FILLING; –

相關問題