take json input from command line and parse the data in java - java

I want to take a (command + JsonData) pattern from command line as input and I don't know how to do it in java. I would be very grateful if anyone can help.
imagine that I have some command + JsonData like this:
addOffering {"code":"81013602","name":"course name","Instructor":"the teacher name",
"units":3,"classTime": {"days": ["saturday","Monday"], "time":"16-17:30"},
"examTime": {"start": "2021-9-01T08:00:00","end": "2021-9-01T08:00:00"},"capacity":60,
"prerequisites": ["Advanced Programming","Operating Systems"]}
in the program I have several commands (like addOffering) so I should take other commands as input.
for taking inputs I am using scanner (but I don't know whether it's a good idea) because i'm new to java.
while(scanner.hasNext()) {
String command = scanner.next();
if(command.equals("exit")) {
break;
}
}
in a while loop I wish to take my inputs and parse command from JsonData to call several functions for different commands and also to initialize my classes fields by the Json data using object mapper(jackson). any help would be greatly appreciated.

Related

Parts of Speech Tagging in JAVA NLP

First of, I am not asking for codes. I will be just asking for suggestions or ideas on how to start this project so please help me I want to learn.
INPUT TEXT FILE:
Five little monkeys jumping on the bed
One fell off and bumped his head
Mama called the doctor and the doctor said:
"No more monkeys jumping on the bed!"
OUTPUT:
Noun:
Monkeys
Doctor
(and other parts of speech)
If i remove one word from the text file it will also be gone from the Output. Is this program possible without downloading anything like the Stanford? I'm using Java. I don't know how to start it without ideas :(
Question:
What method am I going to use.
EDIT!!!!!!!!!!!
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new FileReader("C:/Users/xxxx/Desktop/lyrics.txt"));
String line = null;
while ((line = br.readLine()) != null)
{
System.out.println("Noun: ");
}
}
}
HERE NOW IT ALREADY READS MY TEXTFILE. I thought of an idea that i can just find a specific word in the text file and print it out as, "Noun: Monkeys" but without the user input. What i'm talking about is something like this one
Type word to find: ExampleWord
Output:
Sys.out.print( word + "Found!");
Can do something like this without asking for the user? It will just automatically print out every word?

How to compare a element in String array in Android?

I have a String array as follows:
String [] str_cmd_arr={"cmd1", "cmd2"};
Given that, "cmd1" will output "perform command 1", while "cmd2" will output "perform command 2".
From my str_cmd_arr, how can I print the outputs individually in Java/Android? Currently, I am using this code
for (int i=0;i<str_cmd_arr.length;i++){
if(i<1){
Log.d("TAG","perform command 1");
}
else{
Log.d("TAG","perform command 2");
}
}
The real solution here: use a Map, like
Map<String, String> commandsAndOutput = new HashMap<>();
commandsAndOutput.put("cmd1", "cmd1 output");
...
to later do
String output = commandsAndOutput.get("cmd1");
for example.
Another, probably more sane way here: consider using enums, like:
public enum Command {
CMD1, CMD2;
}
if you are looking for more "compile time" support when making choices between different commands. As you now can write down:
Command cmd = ...
switch(cmd) {
case(CMD1) : ...
But another word of warning: one should be careful about such enum/switching code. In most situations, a "real OO based" design that works with an abstract base class Command and specific subclasses is the better choice.
The real lesson here: you want to study some basics, like the tutorials found here. You see, there is no point in programming for Android ... if you don't know about such basic things such as Maps. In that sense it is hard to give you "good" advise, as the "good" stuff is that abstract base class solution - which seems to be completely beyond your current skills.
Replace your if statement with
if(str_cmd_arr[i]).equals("cmd1"){
You can use a loop and a switch statement
for example
for (int i=0;i<str_cmd_arr.length;i++){
switch(str_cmd_arr[i]) {
case "cmd1":
Log.d("TAG","perform command 1");
break;
case "cmd2":
Log.d("TAG","perform command 2");
break;
}
}

Best way to parse commands in a java text-based game

I'm developing a text based game in java and I'm looking for the best way to deal with player's commands. Commands allow the player to interact with the environment, like :
"look north" : to have a full description of what you have in the north direction
"drink potion" : to pick an object named "potion" in your inventory and drink it
"touch 'strange button'" : touch the object called 'strange button' and trigger an action if there is one attached to it, like "oops you died..."
"inventory" : to have a full description of your inventory
etc...
My objective is now to develop a complete set of those simple commands but I'm having trouble to find an easy way to parse it. I would like to develop a flexible and extensible parser which could call the main command like "look", "use", "attack", etc... and each of them would have a specific syntax and actions in the game.
I found a lot of tools to parse command line arguments like -i -v --verbose but none of them seems to have the sufficient flexibility to fit my needs. They can parse one by one argument but without taking into account a specific syntax for each of them. I tried JCommander which seems to be perfect but I'm lost between what is an argument, a parameter, who call who, etc...
So if someone could help me to pick the correct java library to do that, that would be great :)
Unless you're dealing with complex command strings that involve for instance arithmetic expressions or well balanced parenthesis I would suggest you go with a plain Scanner.
Here's an example that I would find readable and easy to maintain:
interface Action {
void run(Scanner args);
}
class Drink implements Action {
#Override
public void run(Scanner args) {
if (!args.hasNext())
throw new IllegalArgumentException("What should I drink?");
System.out.println("Drinking " + args.next());
}
}
class Look implements Action {
#Override
public void run(Scanner args) {
if (!args.hasNext())
throw new IllegalArgumentException("Where should I look?");
System.out.println("Looking " + args.next());
}
}
And use it as
Map<String, Action> actions = new HashMap<>();
actions.put("look", new Look());
actions.put("drink", new Drink());
String command = "drink coke";
// Parse
Scanner cmdScanner = new Scanner(command);
actions.get(cmdScanner.next()).run(cmdScanner);
You could even make it fancier and use annotations instead as follows:
#Retention(RetentionPolicy.RUNTIME)
#interface Command {
String value();
}
#Command("drink")
class Drink implements Action {
...
}
#Command("look")
class Look implements Action {
...
}
And use it as follows:
List<Action> actions = Arrays.asList(new Drink(), new Look());
String command = "drink coke";
// Parse
Scanner cmdScanner = new Scanner(command);
String cmd = cmdScanner.next();
for (Action a : actions) {
if (a.getClass().getAnnotation(Command.class).value().equals(cmd))
a.run(cmdScanner);
}
I don't think you want to parse command line arguments. That would mean each "move" in your game would require running a new JVM instance to run a different program and extra complexity of saving state between JVM sessions etc.
This looks like a text based game where you prompt users for what to do next. You probably just want to have users enter input on STDIN.
Example, let's say your screen says:
You are now in a dark room. There is a light switch
what do you want to do?
1. turn on light
2. Leave room back the way you came.
Please choose option:
then the user types 1 or 2 or if you want to be fancy turn on light etc. then you readLine() from the STDIN and parse the String to see what the user chose. I recommend you look at java.util.Scannerto see how to easily parse text
Scanner scanner = new Scanner(System.in);
String userInput = scanner.readLine();
//parse userInput string here
the fun part of it is to have some command is human readable, which at the same time, it's machine parsable.
first of all, you needs to define the syntax of your language, for example:
look (north|south|east|west)
but it's in regular expression, it's generally speaking not a best way to explain a syntactical rule, so i would say this is better:
Sequence("look", Xor("north", "south", "east", "west"));
so by doing this, i think you've got the idea. you need to define something like:
public abstract class Syntax { public abstract boolean match(String cmd); }
then
public class Atom extends Syntax { private String keyword; }
public class Sequence extends Syntax { private List<Syntax> atoms; }
public class Xor extends Syntax { private List<Syntax> atoms; }
use a bunch of factory functions to wrap the constructors, returning Syntax. then you will have something like this eventually:
class GlobeSyntax
{
Syntax syntax = Xor( // exclusive or
Sequence(Atom("look"),
Xor(Atom("north"), Atom("south"), Atom("east"), Atom("west"))),
Sequence(Atom("drink"),
Or(Atom("Wine"), Atom("Drug"), Atom("Portion"))), // may drink multiple at the same time
/* ... */
);
}
or so.
now what you need is just a recursive parser according to these rules.
you can see, it's recursive structure, very easy to code up, and very easy to maintain. by doing this, your command is not only human readable, but machine parsable.
sure it's not finished yet, you needs to define action. but it's easy right? it's typical OO trick. all to need to do is to perform something when Atom is matched.

Why doesn't Eclipse always register Ctrl+z in the following piece of code

I'm writing a Java program and I have this section of code in the initialization part of my code:
while (container!=null) {
sb.append(container);
container = reader.readLine();
}
System.out.println("go")
When I run the program, type some strings in standard input and when I press CTRL+Z(I'm working in Windows) it doesn't print "go", basically it's like it never registered. I noticed this happens when first couple of input strings are empty e.g., this input will work:
input
that
works
(CTRL+Z)
This input won't work:
input
that
doesn't work
(CTRL+Z)
Any help would be appreciated.
Can you not try:
while(container != null && !container.equals("")) {
sb.append(container);
container = reader.readLine();
}
System.out.println("go")

REGEX to get flags from console command?

I'm trying to get a regex that can pull out the flags and values in string. Basically, I need to be able to take a string like this:
command -aparam -b"Another \"quoted\" param" -canother one here
And capture the data:
a param
b Another "quoted" param
c another one here
Here is my Java regex so far:
(?<= -\w)(?:(?=")(?:(?:")([^"\\]*(?:\\.[^"\\]*)*)(?="))|.*?( -\w|$))?
But is doesn't quite work yet. Any suggestions?
The suggestion is to use one of available CLI parsers. For example CLI from Jakarta or, better, args4j.
Tokenize the string into command and its parameters using split method,
String input = "command -aparam -b\"Another \"quoted\" param\" -canother one here ";
String[] cmds = input.split("\\s*-(?=\\w)");

Categories

Resources