gpt4 book ai didi

java - 由于某种原因,Switch 语句与情况 8 不同。编译器表现得很奇怪

转载 作者:行者123 更新时间:2023-12-01 07:11:48 24 4
gpt4 key购买 nike

这是代码:

public static void main(String args[])
{
int i=0;
int m=0;
double scale;
boolean exit;
Shape[] s = new Shape[10];
while(exit !=true)
{
System.out.print("\nChoose an option:\n"+
"1-Add a new circle\n"+
"2-Add a new rectangle\n"+
"3-Delete all shapes\n"+
"4-Scale all shapes\n"+
"5-Display perimeter of all shapes\n"+
"6-Display the area of all shapes\n"+
"7-Enter scale factor\n"+
"8-Exit program\n");

Scanner input = new Scanner(System.in);
m=input.nextInt();


if(i<=9)
{
switch (m)
{


case 1: Circle c = new Circle(0);
s[i]=c;
i++;
break;
case 2: Rectangle r = new Rectangle(1,1);
s[i]=r;
i++;
break;

case 3: s=null;
i=0;
break;
case 4: for(i=0; i<s.length; i++)
{
s[i].scaleShape();
}
break;
case 5: for(i=0; i<s.length; i++)
{
if(s[i] != null)
{
System.out.println(s[i].getPerimeter());
}
}
break;
case 6: for(i=0; i<s.length; i++)
{
if(s[i] != null)
{
System.out.println(s[i].getArea());
}
}
break;
case 7: do
{
System.out.println("\nEnter scale factor");
scale=input.nextDouble();
}
while(scale<0);
Shape.setScaleFactor(scale);

}
break;

case 8: System.out.println("Do you want to quit?");
break; //Nothing here since loop should terminate it.



//default: System.out.println("Number must be 1-8");
// break;


}

}
}
}

奇怪的是,编译器在第 8 种情况下给了我一个错误:

Type mismatch can't convert from int to boolean.

但我没有将任何内容转换为 boolean 值

-syntax error on token "case" assert expected -syntax error on token :, ; expected

但是那里的所有命令都有分号

expression must return a value

为什么编译器的行为如此有趣?通常这样的错误很容易发现。这是怎么回事?

最佳答案

您的问题是在 7 的情况下:

case 7: do
{
System.out.println("\nEnter scale factor");
scale=input.nextDouble();
}
while(scale<0);
Shape.setScaleFactor(scale);

}

请注意额外的右大括号:它会关闭您的 switch 语句,从而孤立您的 case 8

关于java - 由于某种原因,Switch 语句与情况 8 不同。编译器表现得很奇怪,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12831571/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com