编译器一直说我的if else语句出错了,我无法弄明白为什么。
import java.util.Scanner;
public class PackingOrganizer{
public static void main(String[] args){
int cartons = 4, boxes = 5;
Scanner input = new Scanner(System.in);
System.out.print("Enter number of items : (All partial items are to be rounded up. ex. 6.5 items is rounded to 7 items)");
double itemcount = input.nextDouble();
if (itemcount != (int) itemcount);
System.out.println("Invalid input round all partial numbers up");
else if (itemcount % cartons = 0){
int containerAmount =( itemcount \ cartons );
System.out.println("Cartons can be used. The" + itemcount + " items will require " + containeramount + " cartons. ");}
}
}
}
答案 0 :(得分:5)
实际上有几个错误:
\
不是分割符号,/
是itemcount
为double
,除以int
后我们得到double
,但containerAmount
被声明为int
itemcount % cartons = 0
不是有效的布尔表达式,您可能需要itemcount % cartons == 0
containerAmount
已声明,但引用了containeramount
建议:尝试使用一些语法突出显示并动态编译IDE。我可以推荐eclipse或IntelliJ IDEA
答案 1 :(得分:0)
您需要进行一些更改:
public static void main(String[] args) {
int cartons = 4, boxes = 5;
Scanner input = new Scanner(System.in);
System.out.print("Enter number of items : (All partial items are to be rounded up. ex. 6.5 items is rounded to 7 items)");
double itemcount = input.nextDouble();
if (itemcount != (int) itemcount) {
System.out.println("Invalid input round all partial numbers up");
} else if (itemcount % cartons == 0) {
int containerAmount = (int) (itemcount / cartons);
System.out.println("Cartons can be used. The" + itemcount + " items will require " + containerAmount+ " cartons. ");
}
}
答案 2 :(得分:0)
您的;
之后就有if (itemcount != (int) itemcount)
。这意味着if
您的条件为真,不会做任何事情,然后System.out.println("Invalid input round all partial numbers up");
将始终执行。但是,还有一个else
现在无法找到它所附加的iff,因为if
后面有两个语句而没有大括号({}
)。为了避免这些错误,我建议总是使用这样的大括号:
if (itemcount != (int) itemcount) {
System.out.println("Invalid input round all partial numbers up");
}
...
这可以帮助您避免这些类型的编译失败。