【发布时间】:2017-03-02 04:46:41
【问题描述】:
程序应该为不同的形状运行计算,因为不同的情况嵌套在一个while循环中。代码如下:
package Lab_7;
import java.util.*;
public class compar {
public static void main(String [] args){
Scanner d = new Scanner(System.in);
boolean start = true;
while(start){
System.out.print("Would you like to start the program?: ");
String answer1 = d.nextLine();
switch (answer1){
case "yes":
System.out.println("Which shape would you like to use to compute area/perimeter?: ");
String answer2 = d.nextLine();
if(answer2.equals("circle")){
try{
System.out.print("Enter radius: ");
int answer3 = d.nextInt();
Circle c = new Circle(answer3);
double area = c.computeArea();
double perimeter = c.computePerimeter();
System.out.println("Area = " + area + " & perimter = " + perimeter );
break;
}
catch(Exception e){
System.out.println("Error!");
break;
}
}
case "no":
System.out.println("Program Terminating...");
start = false;
break;
default:
System.out.println("bug");
continue;
}
}
d.close();
}
}
但是,在第一次成功运行后,程序应该循环回到开头(要求用户启动程序?),但是却发生了这种情况:
Would you like to start the program?: yes
Which shape would you like to use to compute area/perimeter?:
circle
Enter radius: 10
Area = 314.16 & perimter = 62.832
Would you like to start the program?: bug
Would you like to start the program?:
我可以使用一堆 if 语句,但我真的需要知道为什么在第一次成功运行后,我的程序:
- 跳过所有情况并执行默认语句,然后循环回到第一个打印语句,最后等待输入?
【问题讨论】:
-
因为这个
in.nextInt();包含一个字符串字符\n所以它会跳过下一个in.nextLine()你想尝试把in.nextLine()放在in.nextInt()之后 -
case "yes"末尾缺少break语句。 -
@Smit 你把它完全背对了。
nextInt()确实不 包含换行符,并且将不 跳过下一个nextLine(),因此要求是通过添加nextLine()调用来使用换行符。你的解释毫无意义。 -
@EJP 感谢您的纠正。感谢您的反馈。下次会注意的。
标签: java while-loop switch-statement case default