0

The below code works just fine. But how can I get the user to input a string instead of and int to bring up either the "shop" or "inn" method?

ie. When "int a = navigate.nextInt();" is changed to "String a = navigate.nextString();" and the "if" and "if else" conditions are changed to "a == "shop" or "inn". The next line to run the correct method does nothing.

(I hope that made sense, see below)

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?");

}

}

Jimmy
  • 27,142
  • 5
  • 87
  • 100
  • See https://stackoverflow.com/questions/513832/how-do-i-compare-strings-in-java - and just for the sake of it, use `#nextLine`, as `#nextString` is not a method supported by `Scanner`. – Kristin Jan 31 '18 at 15:15
  • 3
    Possible duplicate of [How do I compare strings in Java?](https://stackoverflow.com/questions/513832/how-do-i-compare-strings-in-java) – Kristin Jan 31 '18 at 15:17

2 Answers2

0

Try this

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

            if (a.equals("Shop")) 
                Shop();
            else if (a.equals("Inn")) 
                Inn();
        }
ardi4n
  • 131
  • 5
0

Use .equal

  • == tests for reference equality (whether they are the same object).

  • .equal tests for value equality (whether they are logically "equal").

More: How do I compare strings in Java?

pi.314
  • 622
  • 5
  • 16