MineralTea

2017-01-20 03:15 阅读 1.0k

java题目这样做为什么三角形部分无法构成三角型时会死循环

2
``````package student;
import java.util.Scanner;
public class mianji {
public static void main(String[] args){
System.out.println("形状的类型\n1.长方形\n2.圆形\n3.三角形\n4.退出");
Scanner scan=new Scanner(System.in);
int a=scan.nextInt();
if(a<=4&&a>=1){
switch(a){
case 1:
float b=scan.nextFloat();
float c=scan.nextFloat();
if(b>=0&&c>=0){
System.out.println("Area of the rectangle is:"+(c*b));
}else{System.out.println("b and c can't be zero");}
case 2:
float d=scan.nextFloat();
if(d>=0){
System.out.println("Area of the cylnder is:"+(d*d*Math.PI));
}else{System.out.println("d can't be zero");}
case 3:
System.out.println("Plese enter A");
float A=scan.nextFloat();
System.out.println("Plese enter B");
float B=scan.nextFloat();
System.out.println("Plese enter C");
float C=scan.nextFloat();
if(A>=0&&B>=0&&C>=0){
while(true){if(A+B>C){
float p=(A+B+C)/2;
float sum=(float) Math.sqrt((p*(p-A)*(p-B)*(p-C)));
System.out.println("The triangle area is "+sum);
}
else{
System.out.println("Three sides can not constitute a triangle");
}
}}else{
System.out.println("A,B,C can't be zero");
}
case 4:
System.out.println("Bye Bye");
}

}
else{
}
}

}
``````

• 点赞
• 写回答
• 关注问题
• 收藏
• 复制链接分享

5条回答默认 最新

• 小黄人的banana 2017-01-20 03:26

我记得swtich是要加break的

点赞 评论 复制链接分享
• 逗比123号 2017-01-20 03:31

public static void main(String[] args) {

``````System.out.println("形状的类型\n1.长方形\n2.圆形\n3.三角形\n4.退出");
Scanner scan=new Scanner(System.in);
boolean flag = true;
while(scan.hasNextInt()&&flag==true){
int a=scan.nextInt();
if(a<=4&&a>=1){
switch(a){
case 1:
float b=scan.nextFloat();
float c=scan.nextFloat();
if(b>=0&&c>=0){
System.out.println("Area of the rectangle is:"+(c*b));
}else{System.out.println("b and c can't be zero");}
break;
case 2:
float d=scan.nextFloat();
if(d>=0){
System.out.println("Area of the cylnder is:"+(d*d*Math.PI));
}else{System.out.println("d can't be zero");}
break;
case 3:
System.out.println("Plese enter A");
float A=scan.nextFloat();
System.out.println("Plese enter B");
float B=scan.nextFloat();
System.out.println("Plese enter C");
float C=scan.nextFloat();
if(A>=0&&B>=0&&C>=0){
if(A+B>C&&B+C>A&&A+C>B){
float p=(A+B+C)/2;
float sum=(float) Math.sqrt((p*(p-A)*(p-B)*(p-C)));
System.out.println("The triangle area is "+sum);
} else{
System.out.println("Three sides can not constitute a triangle");
}
}else{
System.out.println("A,B,C can't be zero");
}
break;
case 4:
System.out.println("Bye Bye");
flag=false;
break;
}

}
else{
}
``````

}
}

``````
``````
点赞 评论 复制链接分享
• csdncqmyg 2017-01-20 03:51

case 3里的while（true ） =死循环，里面的逻辑函数完成后应该有break跳出循环

点赞 评论 复制链接分享
• 隔壁大颜子 2017-01-20 05:30

switch里面是要加break的吧

点赞 评论 复制链接分享
• 蚂蚁冲锋队 2017-01-21 01:12

问题1、switch中每个case都要有对应的break；
switch(id){
case 0x01：
funcA();
break;

case 0x02：
funcB();
break;
}
问题2、
if(A>=0&&B>=0&&C>=0){
while(true){if(A+B>C){
float p=(A+B+C)/2;
}
}
}
逻辑有误，只要满足A B C大于0就会进入while(true){}死循环，当不满足三角形边的要求就没有出口break或者return

点赞 评论 复制链接分享