我在面试时被问及以下问题。我被要求使用*
角色进行“填充打印”的形式。下面是我为我的回答(在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();
}
}
有没有更好的更有效除了我的方式之外这么做吗?此外,我在代码中做得不好?
这对我来说真的很重要。我现在正在练习常见的面试编码问题。
http://codereview.stackexchange.com/这个练习的 –
的目标不是让你编写一个“高效”的算法。这只是为了看看你是否理解循环。尽量使其可读性,使用简短的命名方法,使其在间距中保持一致,以便正确缩进代码。而且,循环传统上从Java开始为0。变量在最后一刻声明和初始化,范围最窄。 –
初学者:public final static String CROSS =“x”; public final static String STAR =“*”; - 然后使用System.print(STAR);或CROSS –