优化代码public abstract class MyPrint { public abstract void show(); } public class MyPrintSquare extends MyPrint { @Override public void show() { //打印正方形 for (int i = 0; i < 5; i++) { for (int j = 0; j < 5; j++) { if (j==0||j==4){ System.out.print("*"); }else if (i==0||i==4){ System.out.print("*"); }else { System.out.print(" "); } } System.out.println(); } } } public class MyPrintCircle extends MyPrint { @Override public void show() { //打印圆形 for (int y = 0; y <= 10; y +=2) { int x =(int)Math.round(5-Math.sqrt(10*y-y*y)); int len =2*(5-x); for (int i = 0; i <= x; i++) { System.out.print(" "); } System.out.print("*"); for (int j = 0; j <= len; j++) { System.out.print(" "); } System.out.println("*"); } } } public class Experiment5_1{ public static void main(String[] args) { MyPrint sqrare = new MyPrintSquare(); MyPrint circle = new MyPrintCircle(); sqrare.show(); circle.show(); } }
时间: 2023-06-08 09:09:15 浏览: 76
C++代码优化方案.
这段代码存在一个问题,就是在内部循环语句中的 i 和 j 变量没有被递增,导致死循环。应该在循环体中将变量递增。修改后的代码如下:
public abstract class MyPrint {
public abstract void show();
}
public class MyPrintSquare extends MyPrint {
@Override
public void show() {
//打印正方形
for (int i = 0; i < 5; i++) {
for (int j = 0; j < 5; j++) {
if (j==0||j==4){
System.out.print("*");
}else if (i==0||i==4){
System.out.print("*");
}else {
System.out.print(" ");
}
}
System.out.println();
}
}
}
public class MyPrintCircle extends MyPrint {
@Override
public void show() {
//打印圆形
for (int y = 0; y <= 10; y += 2) {
int x = (int)Math.round(5-Math.sqrt(10*y-y*y));
int len = 2*(5-x);
for (int i = 0; i <= x; i++) {
System.out.print(" ");
}
System.out.print("*");
for (int j = 0; j <= len; j++) {
System.out.print(" ");
}
System.out.println("*");
}
}
}
public class Experiment5_1{
public static void main(String[] args) {
MyPrint sqrare = new MyPrintSquare();
MyPrint circle = new MyPrintCircle();
sqrare.show();
circle.show();
}
}
阅读全文