我在面試時被問及以下問題。我被要求使用*
角色進行「填充打印」的形式。下面是我爲我的回答(在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 –