【问题标题】:How can I use a "String" to compare an "if" and "if else" statement?如何使用“字符串”来比较“if”和“if else”语句?
【发布时间】: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?");

}

}

【问题讨论】:

标签: string methods int call


【解决方案1】:

使用 .equal

  • == 测试引用相等性(它们是否是同一个对象)。

  • .equal 测试值相等(它们是否在逻辑上 “相等”)。

更多:How do I compare strings in Java?

【讨论】:

    【解决方案2】:

    试试这个

    System.out.println("Where to?\n Shop \n  Inn ");
            String a = navigate.nextLine();
    
                if (a.equals("Shop")) 
                    Shop();
                else if (a.equals("Inn")) 
                    Inn();
            }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2022-01-09
      • 1970-01-01
      • 2016-07-17
      • 1970-01-01
      • 2022-11-16
      • 1970-01-01
      • 2016-01-21
      相关资源
      最近更新 更多