以下代码工作得很好。但是我怎样才能让用户输入一个字符串而不是和int来调出" shop"或"旅馆"方法
即。当" int a = navigate.nextInt();"更改为" String a = navigate.nextString();"和#34;如果"和" if else"条件变为" a ==" shop"或"旅馆"。运行正确方法的下一行什么都不做。
(我希望有道理,见下文)
import java.util.*;
public class ShopTest {
public static Scanner navigate = new Scanner(System.in);
public static void main(String[] args) {
System.out.println("Where to?\n Shop (1)\n Inn (2)");
int a = navigate.nextInt();
if (a == 1)
Shop();
else if (a == 2)
Inn();
}
public static void Shop() {
System.out.println("Welcome to my shop\nWould you like to see my wares?");
}
public static void Inn() {
System.out.println("**You enter the inn and approach the barkeep**\nHow can I help you?");
}
}
答案 0 :(得分:0)
试试这个
System.out.println("Where to?\n Shop \n Inn ");
String a = navigate.nextLine();
if (a.equals("Shop"))
Shop();
else if (a.equals("Inn"))
Inn();
}
答案 1 :(得分:0)
使用.equal
==
测试引用相等性(它们是否是同一个对象)。
。价值平等的等价测试(无论它们是否合乎逻辑 "等于"。)