【发布时间】:2018-07-10 18:09:32
【问题描述】:
下面的代码工作得很好。但是如何让用户输入字符串而不是 int 来调出“shop”或“inn”方法?
即。当“int a = navigate.nextInt();”改为“String a = navigate.nextString();”并且 "if" 和 "if else" 条件更改为 "a == "shop" 或 "inn"。运行正确方法的下一行什么也不做。
(我希望这是有道理的,见下文)
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?");
}
}
【问题讨论】:
-
见stackoverflow.com/questions/513832/… - 只是为了它,使用
#nextLine,因为#nextString不是Scanner支持的方法。