Think:
最开始没考虑完整情况 也就是 负数的个数, 不能直接用 break; 最开始 出错在于 -2 -3 的时候 会出现 2个0.00 , 后来 看完代码发现 我在 判断 负数的时候时 是直接 如果出现负数就 break; 所以最后采用读入 整个字符串 然后 以 空格进行分割
Problem Description
定义接口Shape,定义求周长的方法length()。
定义如下类实现接口Shape的抽象方法:
(1)三角形类Triangle (2)长方形类Rectangle (3)圆形类Circle等。
定义测试类ShapeTest,用Shape接口定义变量shape,用其指向不同类形的对象,输出各种图形的周长。并为其他的Shape接口实现类提供良好的扩展性。
Input
输入多组数值型数据(double);
一行中若有1个数,表示圆的半径;
一行中若有2个数(中间用空格间隔),表示长方形的长度、宽度。
一行中若有3个数(中间用空格间隔),表示三角形的三边的长度。
若输入数据中有负数,则不表示任何图形,周长为0。
Output
行数与输入相对应,数值为根据每行输入数据求得的图形的周长(保留2位小数)。
Sample Input
1
2 3
4 5 6
2
-2
-2 -3
Sample Output
6.28
10.00
15.00
12.56
0.00
0.00
Hint
构造三角形时要判断给定的三边的长度是否能组成一个三角形,即符合两边之和大于第三边的规则;
计算圆周长时PI取3.14。
import java.util.Scanner;
import javax.swing.plaf.synth.SynthSpinnerUI;
interface Shape{
double length();
}
class Triangle implements Shape{
double x1, x2, x3;
public Triangle(double x1, double x2, double x3) {
super();
this.x1 = x1;
this.x2 = x2;
this.x3 = x3;
}
public double length() {
if(x1 + x2 <= x3 || x1 + x3 <= x2 || x3 + x2 <= x1)
return 0;
else
return x1 + x2 + x3;
}
}
class Rectangle implements Shape{
double x1, x2;
public Rectangle(double x1, double x2) {
super();
this.x1 = x1;
this.x2 = x2;
}
public double length() {
return 2 * (x1 + x2);
}
}
class Circle implements Shape{
double r;
public Circle(double r) {
super();
this.r = r;
}
public double length() {
return 3.14 * 2 * r;
}
}
public class Main {
public static void main(String[] args){
Scanner cin = new Scanner(System.in);
int i, j;
double[] a = new double[15];
while(cin.hasNext())
{
int cnt = 0;
String str = cin.nextLine();
String[] strs = str.split(" ");
for(i = 0; i < strs.length; i++)
a[i] = Integer.parseInt(strs[i]);
int flag = 1;
if(i == 1)
{
for(j = 0;j <= 0;j ++)
{
if(a[j] <= 0)
{
flag = 0;
break;
}
}
}
if(i == 2)
{
for(j = 0;j <= 1;j ++)
{
if(a[j] <= 0)
{
flag = 0;
break;
}
}
}
if(i == 3)
{
for(j = 0;j <= 2;j ++)
{
if(a[j] <= 0)
{
flag = 0;
break;
}
}
}
if(flag == 0)
System.out.println("0.00");
else
{
if(i == 1)
{
Circle test = new Circle(a[0]);
System.out.printf("%.2f\n", test.length());
}
if(i == 2)
{
Rectangle test = new Rectangle(a[0], a[1]);
System.out.printf("%.2f\n", test.length());
}
if(i == 3)
{
Triangle test = new Triangle(a[0], a[1], a[2]);
System.out.printf("%.2f\n", test.length());
}
}
}
cin.close();
}
}