The java program will Display a welcome message Repeat the following sequence un
ID: 3883548 • Letter: T
Question
The java program will
Display a welcome message
Repeat the following sequence until the “quit” command is entered
Display “Command: “
Gets a line of input
Tokenize the input line
If the first token of the line is “quit”
Then exit the loop and terminate the program
Else process a command
Implement the following commands providing appropriate error messages if used incorrectly:
Pickup item
Drop item
Go direction
Save
Quit
Example output:
Welcome the game!
Command: go north south
Too many arguments!
Command: go north
Going north
Command: pickup
Pick up what?
Command: pickup fork
Fork was picked up
Command: drop axe
axe was dropped
Command: save
Gamed saved
Command: quit
Explanation / Answer
Here is game Java program:
Game Java:
import java.util.Scanner;
class game
{
public static void main(String args[])
{
String Command;
String[] words;
Scanner input=new Scanner(System.in);
System.out.println("Welcome the game!");
while(true)
{
System.out.println("Command: ");
Command=input.nextLine();
words=Command.split("\s+"); //split command into string array
if(words.length>2)
System.out.println("Too Many Arguments!");
else
if(words[0].equals("go"))
System.out.println("Going "+words[1]);
else
if(words[0].equals("pickup"))
{
System.out.println("Pick up What? ");
System.out.println("Command: ");
Command=input.nextLine();
words=Command.split("\s+");
System.out.println(words[1]+" was picked up");
}
else
if(words[0].equals("drop"))
{
System.out.println(words[1]+" was dropped");
}
else
if(words[0].equals("save"))
{
System.out.println("Game saved");
}
else
if(words[0].equals("quit"))
System.exit(0);
}
}
}
I hope this solves your problem
Comment if you have any problem in above code
And please give it a thumbs up if it solved your problem :)
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.