我刚开始使用java,所以如果我犯了一个非常简单的错误,请原谅我。我试图使商店内的文字为基础的冒险游戏。我已经创建了一个数组shopItems,它将项目列表存储为商店可以出售的字符串。下面是我为用户在游戏中购买的方法的一部分。
String request = s.nextLine().toLowerCase();
for (int i = 0 ; i < shopItems.length ; i++)
{
if(request.equalsIgnoreCase(shopItems[i]))
{
System.out.println("We have this item in stock! That will be " + itemPrice[i] + " gold, "
+ "would you like to purchase this item?");
String command2 = s.nextLine().toLowerCase();
if(command2.equals("yes") || command2.equals("y"))
{
if (savings >= itemPrice[i])
{
System.out.println("Congratulations! You have purchased " + shopItems[i] + ". Thank you "
+ "for your business.");
savings = savings - itemPrice[i];
inv.add(shopItems[i]);
magicShopPurchase();
}
else if (savings < itemPrice[i])
{
System.out.println("I'm sorry, you don't have enough gold to purchase this item! Try "
+ "again when you have enough!");
}
}
}
else if(request.equals("leave"))
{
System.out.println("Thank you! Please come again soon!");
inMagicShop();
}
else
{
System.out.println("I'm sorry, we don't have any of those in stock at the moment. Would you "
+ "like to purchase a different item?");
String command2 = s.nextLine().toLowerCase();
if(command2.equals("yes") || command2.equals("y"))
{
magicShopPurchase();
}
else if(command2.equals("no") || command2.equals("n"))
{
System.out.println("Thank you! Please come again soon!");
inMagicShop();
}
else
{
System.out.println("Haha, you kiss your mother with that mouth? Come back some other time!");
inMagicShop();
}
}
}我正在尝试将扫描仪输入与shopItems进行比较,以检查用户想要购买的商品在商店中是否可用,但是它不识别shopItems中的任何元素。我用这种方法做错什么了吗?是不是哪里出了错?这是我在这里的第一篇帖子,如果我遗漏了任何重要的东西,请原谅我。
编辑
首先是调用方法将元素存储到shopItems中的位置。
try {
itemList = new String(Files.readAllBytes(Paths.get("C:\\Users\\gravy_000\\Desktop\\Software Development 1\\GameProject\\src\\hallSim\\magicitems.txt")));
read(itemList);
} catch (IOException e) {
e.printStackTrace();
}第二个是我用来读取文本文件并将其存储到shopItems中的方法。
public static void read(String shopList) {
shopItems = shopList.split("\\r?\\n");
}下面是Dropbox https://www.dropbox.com/s/rbfsr1fj2yzus1q/magicitems.txt?dl=0中文本文件的链接
发布于 2016-04-18 01:01:37
问题是,您是在告诉用户,在第一次request.equalsIgnoreCase(shopItems[i])返回false时,没有找到该项,而不是当request不存在时。
因此,您应该将代码替换为类似于以下或类似的内容:
String request = s.nextLine().toLowerCase();
if(request.equals("leave")) {
//leave
} else {
boolean isItemInStock = false;
for (int i = 0 ; i < shopItems.length ; i++) {
if(request.equalsIgnoreCase(shopItems[i])) {
isItemInStock = true;
break;
}
}
if(isItemInStock) {
System.out.println("We have this item in stock! That will be " + itemPrice[i] + " gold, "
+ "would you like to purchase this item?");
//...
} else {
System.out.println("I'm sorry, we don't have any of those in stock at the moment. Would you "
+ "like to purchase a different item?");
//...
}
}注意在主循环之外是如何处理使用request的if/ with语句的。
https://stackoverflow.com/questions/36683290
复制相似问题