//想要打印出一帧星号。框架整体上必须有16个星号。
public class Patterns {
public static void main(String[] args) {
for(int i=1; i<=4; i++){
for(int j=1; j<=4; i++){
if((i==1||i==4)&&(j==1||j==4)){
System.out.print("*");
}
else{
System.out.print(" ");
}
System.out.println();
}
}
}
}
答案 0 :(得分:0)
这是一个允许您指定宽度和高度的版本:
int width = 5;
int height = 5;
for (int i = 0; i < height; i++) {
for (int j = 0; j < width; j++) {
if (i == 0 || i == height -1) { //first or last line
System.out.print("*");
} else if (j == 0 || j == width -1) { // middle line first or last star
System.out.print("*");
} else { // middle line not on the edge
System.out.print(" ");
}
}
System.out.println(); // start a new line
}
答案 1 :(得分:0)
问题出在if条件 -
if((i==1||i==4)&&(j==1||j==4)){
System.out.print("*");
}
更好的是,您可以尝试更强大的解决方案。您可以在此设置ROW
和COLUMN
来调整框架高度或宽度。使用以下代码,您可以打印矩形框,例如ROW = 15
和COLUMN = 10
。请参阅此处的解决方案 -
public class Frame{
/*You may adjust ROW or COLUMN
* You may print a rectangular frame
* by setting ROW = 6 and COLUMN = 12
*/
private final static int ROW = 4;
private final static int COLUMN = 4;
//Need not to change
private final static int I_MIN = 1;
private final static int I_MAX = ROW;
private final static int J_MIN = 1;
private final static int J_MAX = COLUMN;
public static void main(String[] args) {
//always start from i=1 and j=1
for(int i=1; i<=ROW; i++){
for(int j=1; j<=COLUMN; j++){
if(isOnMargin(i,j)){
System.out.print("*");
}else{
System.out.print(" ");
}
}
System.out.println();
}
}//main()
/*
* This method determine whether an (i,j)
* is on margin. In main method if an (i,j)
* on margin then print "*" or print " ".
*/
private static boolean isOnMargin(int i, int j){
if(i==I_MIN || i==I_MAX){
return true;
}
else if(j==J_MIN || j==J_MAX){
return true;
}
return false;
}
}
希望它会有所帮助 非常感谢。
<强>输出:强>