0

I am currently making a small Java program which features multiple rooms. I am still new to Java so the less complicated the code, the better.

The player has to be able to travel between rooms, but can only do so via the "go (direction)" command, eg: go west.

How do i split this input so i can call my travel method when the player enters "go" as the first part of their input?

At the same time, a direction will need to be registered so the game knows what the next room will be. (Split the second part of the input).

Help will be much appreciated.

Bram Sars
  • 13
  • 2

2 Answers2

0

Sounds like you could use substring in Java and operate on your commands that way :

   String str= new String("quick brown fox jumps over the lazy dog");

   System.out.println("Substring starting from index 15 and ending at 20:");
   System.out.println(str.substring(15, 20));

output:

   Substring starting from index 15 and ending at 20:
   jump

you could also use regular expressions along with split like this :

        public static void main(String[] args) {



        String str = "abdc124psdv456sdvos456dv568dfpbk0dd";



        // split the array using a single digit, e.g 1,2,3...

        String[] parts = str.split("[0-9]");

        System.out.println(Arrays.toString(parts));


        // split the array using a whole number, e.g  12,346,756

        parts = str.split("[0-9]+");

        System.out.println(Arrays.toString(parts));

    }

link: using split with regex

link : using substring

timi95
  • 368
  • 6
  • 23
0

Based on your description the input will be go west or go east or go south or go north, suppose if we have string with value go west

String input = "go west";

Then split input string based on space delimiter will return String array

String[] dir = input.split(" ");
dir[0] // will be `go`
dir[1] // will be direction `west`

Then compare dir[0] using equals() method, if true call the method with direction

if(dir[0].equals("go")){
   //action
   }
Ryuzaki L
  • 37,302
  • 12
  • 68
  • 98
  • I would use String.spit(" +") (empty space followed by plus). Since split uses regex you could handle the situation that someone enters more than one space. – mayamar Jan 12 '19 at 21:02
  • This seems to work, thanks.EDIT: does it also work with a scanner? if so, do you know how? – Bram Sars Jan 12 '19 at 22:16
  • I know, but you should give a try, it's so simple just google it, try and if you stuck at any point post the code i will help you out – Ryuzaki L Jan 12 '19 at 22:18