I’m trying to write a simple and quick text-based java dungeon crawler.
The player can type in simple 3 letter commands followed by a number value like this:
NTH 21, or ATT 3, or CST 102, etc…
I know how to get the first 3 letter command using substring()
.
I also know I can use substring()
to get the end of a string like this:
amount = gameInput.substring(gameInput.length() - 3)
But I’m not sure how to handle it since the amount can be any size of number like 1, or 28, 490, 4329, etc…
Here is what I have so far:
// example move commands 'NTH 10', 'EST 3', 'WST 320', 'STH 11' // example combat commands 'ATT 333', 'CST 7102', 'STH 4' system.out.print("Enter your character action and value amount: "); system.out.print("n ** Enter 'END 9' to end game **"); while(userInput != "END 9") { gameInput = myScanner.nextLine(); // character action direction = gameInput.substring(0, 2); // action amount amount = }
Thanks!
Advertisement
Answer
use String#split like:
String[] args = userInput.split(" ");
it will split the string by space.
then to get the last argument use:
String lastArg = args[args.length - 1];
I hope I helped 🙂