2013-11-28 120 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; –

相关问题