悦然无殇
2017-05-20 12:11
//父类代码。
public abstract class shape {
public abstract void length();
public abstract void square();
}
//长方形子类代码。
public class rectangle extends shape {
Scanner scan1=new Scanner(System.in);
int l=scan1.nextInt();
Scanner scan2=new Scanner(System.in);
int w=scan2.nextInt();
public void length() {
int length=2*(l+w);
System.out.println("长方形的周长为:"+length);
}
public void square() {
int square=w*l;
System.out.println("长方形的面积为:"+square);
}
}
//圆形子类代码。
public class circle extends shape {
Scanner scan1=new Scanner(System.in);
double r=scan1.nextDouble();
public void length() {
double length=2*3.14*r;
System.out.println("圆形的周长为:"+length);
}
public void square() {
double square=3.14*r*r;
System.out.println("圆形的面积为:"+square);
}
}
//测试类代码。
public class test {
public static void main(String[] args) {
System.out.println("请输入您要查询的图形类型:1代表长方形,2代表圆形。");
Scanner input =new Scanner(System.in);
int num=input.nextInt();
switch (num) {
case 1:
System.out.println("请依次输入长方形的长度和宽度:");
shape shp1=new rectangle();
shp1.length();
shp1.square();
break;
case 2:
System.out.println("请输入圆形的半径:");
shape shp2=new circle();
shp2.length();
shp2.square();
break;
default:
System.out.println("您输入的数值有误,请重新输入。");
}
}
}我想要的改进是:在用户输入其他数值显示错误后,不用重新运行程序就可以接着接着重新输入,直到是1或者2
//测试类代码。
public class test {
public static void main(String[] args) {
//定义一个flag布尔变量
boolean flag = true;
while(flag){
System.out.println("请输入您要查询的图形类型:1代表长方形,2代表圆形。");
Scanner input =new Scanner(System.in);
int num=input.nextInt();
switch (num) {
case 1:
System.out.println("请依次输入长方形的长度和宽度:");
shape shp1=new rectangle();
shp1.length();
shp1.square();
flag = false;
break;
case 2:
System.out.println("请输入圆形的半径:");
shape shp2=new circle();
shp2.length();
shp2.square();
flag = false;
break;
default:
System.out.println("您输入的数值有误,请重新输入。");
}
}
}
}
先定义一个布尔变量,初始值为true,使用while循环无限循环。当switch条件匹配,则改变flag变量的值为false,
然后break退出switch语句.此时while循环条件不成立,所以停止循环。反之,若switch没有匹配将不会改变flag的值
则不会停止循环.
还有,我提醒一句,你的长方形子类的创建Scanner对象,可以只创建一个。使用同一对象调用方法。
编写一个登录界面也可以采用这个思路,很棒
Java入门第二季
531293 学习 · 6327 问题
相似问题