我不知道为什么我得到'else没有if'错误。我的格式是正确的。
if(donationType>2)
{
if(donationType == CLOTHING_CODE)
{
volunteer = CLOTHING_PRICER;
message = "a clothing donation";
}
else
{
volunteer = OTHER_PRICER;
message = "a non-clothing donation";
}
else
message = "This is an invalid donation type";
message = "The volunteer who will price this item is invalid";
}
else后面缺少一个大括号
if(donationType>2)
{
if(donationType == CLOTHING_CODE)
{
volunteer = CLOTHING_PRICER;
message = "a clothing donation";
}
else
{
volunteer = OTHER_PRICER;
message = "a non-clothing donation";
}
}
else
{
message = "This is an invalid donation type";
message = "The volunteer who will price this item is invalid";
}
您缺少第一个else
的右括号}
,因此您打算结束第一个if
的}
实际上结束了else
,因此您连续有2个else
,因此出现错误。
补上缺少的结束大括号}
(并为最后一个else
补上开始大括号{
)。
每个代码块总是需要正确地打开和关闭。
else
{
volunteer = OTHER_PRICER;
message = "a non-clothing donation";
/*YOU'RE MISSING AN ENDING BRACE HERE*/
您缺少一个}
:
else
{
volunteer = OTHER_PRICER;
message = "a non-clothing donation";
}
// ^ was missing
}
看一下W3School,你少了一个括号
if (condition1) {
block of code to be executed if condition1 is true
} else if (condition2) {
block of code to be executed if the condition1 is false and condition2 is true
} else {
block of code to be executed if the condition1 is false and condition2 is false
}
有两个问题:
问题1:
忘记关闭else部分
else
{
volunteer = OTHER_PRICER;
message = "a non-clothing donation";
问题2:
你忘记打开else分支,当你正确关闭它时
else
message = "This is an invalid donation type";
message = "The volunteer who will price this item is invalid";
}
修改后,你的代码应该是
if(donationType>2)
{
if(donationType == CLOTHING_CODE)
{
volunteer = CLOTHING_PRICER;
message = "a clothing donation";
}
else
{
volunteer = OTHER_PRICER;
message = "a non-clothing donation";
} // I added this
}
else { // I added this
message = "This is an invalid donation type";
message = "The volunteer who will price this item is invalid";
}