for-my-if语句中的java循环不能产生我想要的结果
大家好,当我尝试访问代码时发生了以下情况,第一部分很好,因为没有库存中的手提包,我希望它说你正在携带,但是如果我有手提包,我希望它说你正在手提包中携带这些物品,但以下情况会发生
现在怎么办? 获取火炬 嗯
现在怎么办? 列表 您携带: 火炬
现在怎么办? 走楼梯 这里很黑
现在怎么办? 拿手提包 嗯
What now?
list
You are carrying these items in your handbag:
torch
You are carrying these items in your handbag:
wallet
You are carrying these items in your handbag:
keys
You are carrying these items in your handbag:
ring
You are carrying these items in your handbag:
USB
You are carrying these items in your handbag:
mobile
You are carrying these items in your handbag:
handbag
这是代码
public void listWhatYouHave()
{
for (int i = 0; i < 7; i++)
{
if (hasItem[6])
{
System.out.println("You are carrying these items in your handbag:");
switch (i)
{
case 0:
System.out.println("torch");
break;
case 1:
System.out.println("wallet");
break;
case 2:
System.out.println("keys");
break;
case 3:
System.out.println("ring");
break;
case 4:
System.out.println("USB");
break;
case 5:
System.out.println("mobile");
break;
case 6:
System.out.println("handbag");
break;
default:
System.out.println("invalid item!");
break;
}
}
else if (hasItem[i])
{
System.out.println("You are carrying:");
switch (i)
{
case 0:
System.out.println("torch");
break;
case 1:
System.out.println("wallet");
break;
case 2:
System.out.println("keys");
break;
case 3:
System.out.println("ring");
break;
case 4:
System.out.println("USB");
break;
case 5:
System.out.println("mobile");
break;
case 6:
System.out.println("handbag");
break;
default:
System.out.println("invalid item!");
break;
}
}
}
你能帮忙吗。。。谢谢(这显然是java)
对不起,贝尼格。。。几乎在我没有手提包的时候,我想让它列出我携带的东西,说“你正在携带”,但是如果我在提包的时候拿起手提包。。。我想让它说‘你在手提包里带着这些东西’,但现在它只打印出你带着一次。。。但是你的手提包里有这些东西,而且是用everyline打印的。。。我只想要一次
# 1 楼答案
您的
hasItem[6]
值为true,则if (hasItem[6])
条件将始终为true。 你的其他部分不会被执行可能您需要
if(hasItem[i])
而不是if(hasItem[6])
# 2 楼答案
我认为问题在于,在你状态的第一部分,你只检查用户是否有hadbag,而不检查物品。应重写第一个条件:
同时,我会重构出内部开关,因为它在代码中有两次。我建议使用枚举类型而不是整数常量
编辑:
为了防止它多次打印“youareholding”行,您应该从for循环中重构它
我会这样做:
此外,如果您不想写下手提包中携带的手提包,您可以将其从开关盒中取出,因为它是用于不同用途的