我一直在努力将这个问题正确编码好一个小时,我无法弄明白。这种方法用成人票,学生票,如果它是一个日场,如果它是在工作日,以及他们将要看的电影,计算去看电影的成本。
首先,我在每个if语句之后放入一个return语句,它说该方法没有return语句。现在,我把它放在方法的末尾,并且无法识别变量 cost ,因为 cost 在if语句中。
对所有文字感到抱歉。这是代码。
public static int getCost (char movie, int month, int day, boolean isMatinee, int numberOfAdultTickets, int numberOfStudentTickets)
{
if (movie == 'C')
{
if (isWeekday(month, day))
{
if (isMatinee)
{
int cost = (numberOfAdultTickets*8) + (numberOfStudentTickets*8);
}
else if (!isMatinee)
{
int cost = (numberOfAdultTickets*10) + (numberOfStudentTickets*8);
}
}
else if (!isWeekday(month, day))
{
if (isMatinee)
{
int cost = (numberOfAdultTickets*11) + (numberOfStudentTickets*11);
}
if (!isMatinee)
{
int cost = (numberOfAdultTickets*13) + (numberOfStudentTickets*11);
}
}
}
else if (movie == 'G')
{
if (isWeekday(month, day))
{
if (isMatinee)
{
int cost = (numberOfAdultTickets*6) + (numberOfStudentTickets*6);
}
else if (!isMatinee)
{
int cost = (numberOfAdultTickets*8) + (numberOfStudentTickets*6);
}
}
else if (!isWeekday(month, day))
{
if (isMatinee)
{
int cost = (numberOfAdultTickets*9) + (numberOfStudentTickets*9);
}
else if (!isMatinee)
{
int cost = (numberOfAdultTickets*11) + (numberOfStudentTickets*9);
}
}
}
else if (movie == 'P')
{
if (isWeekday(month, day))
{
if (isMatinee)
{
int cost = (numberOfAdultTickets*6) + (numberOfStudentTickets*6);
}
else if (!isMatinee)
{
int cost = (numberOfAdultTickets*8) + (numberOfStudentTickets*6);
}
}
else if (!isWeekday(month, day))
{
if (isMatinee)
{
int cost = (numberOfAdultTickets*9) + (numberOfStudentTickets*9);
}
else if (!isMatinee)
{
int cost = (numberOfAdultTickets*11) + (numberOfStudentTickets*9);
}
}
}
return cost;
}
答案 0 :(得分:1)
您需要在方法范围中声明成本变量,在if语句之外,例如
int cost = 0;
if (movie == 'C')
{
if (isWeekday(month, day))
{
if (isMatinee)
{
cost = (numberOfAdultTickets*8) + (numberOfStudentTickets*8);
}
else if (!isMatinee)
{
cost = (numberOfAdultTickets*10) + (numberOfStudentTickets*8);
}
}
} else if... //rest of your code.
return cost;
}
答案 1 :(得分:0)
这解决了您的问题:
public static int getCost (char movie, int month, int day, boolean isMatinee, int numberOfAdultTickets, int numberOfStudentTickets)
{
int cost = 0
//there will be the rest of code you already have
}
然而,最大的问题是,如果 - 其他疯狂:)。看看如何使用类。