Java 项目程序错误,我根本无法理解
编译器一直说我的if-else语句有错误,我不知道为什么Java 项目程序错误,我根本无法理解,java,debugging,Java,Debugging,编译器一直说我的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 n
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. ");}
}
}
}
实际上有几个错误:
- if子句后面的分号
不是除法符号,\
是除法符号/
是itemcount
,将其除以double
我们得到int
,但是double
被声明为containerAmount
int
不是有效的布尔表达式,您可能需要itemcount%cartons=0
itemcount%cartons==0
- 输入错误:声明了
,但引用了containerAmount
containerAmount
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. ");
}
}
你有一个
代码>就在您的if(itemcount!=(int)itemcount)
之后。这意味着如果您的条件为true,则不会执行任何操作,然后System.out.println(“无效输入将所有部分数字向上舍入”)代码>将始终执行。但是还有一个else
,它现在找不到它所附加的iff,因为if
后面有两个语句,并且没有大括号({}
)。为了避免此类错误,我建议始终使用如下大括号:
if (itemcount != (int) itemcount) {
System.out.println("Invalid input round all partial numbers up");
}
...
这可以帮助您避免此类编译失败。您看到了什么错误信息?请在if语句后删除分号。我删除了分号,但它仍然不起作用。elseif语句为红色。它说意外类型必需变量find value你真的应该在if和else块周围放上大括号。我已经删除了它,但它仍然没有work@JimJANES:“不起作用”告诉我们可以用来帮助你的东西很少。您看到了哪些新的错误或问题?你能发布最新的代码吗?请帮助我们帮助您。好的,谢谢您添加更多信息。看来它现在可以用了,非常感谢。