java jar accept multiple arguments on runtime - java

I have a java jar that need to accept about 3 arguments but I want to pass them as a Q&A type like the following:
1st step run java jar
java -jar myTest.java
2nd step ask questions and wait for answers:
Hi, how old are you?
I type my answer that accepts it and then ask the 2nd question:
nice! what is your name?
type my second answer and the get a third question and so on. how do I achieve this? I know that I can pass arguments to main but what I found is that I have to pass them all when I first run the jar not like what I'm looking for.
Any ideas?
Thanks!

the way to interact with an application depends of the logic in the application itself...
if you need to give parameters that the application needs from the start point then you give those as soon as you run the application
java -jar myTest.java
all those parameters are getting passed to the string[] parameter in the public static void main method...
in your case, (and if I got the question right) you will need more information from the user, and this is given at runtime... so you need another way to do that like Scanner class allowing you to read input from the terminal too...
Use the Scanner class and read the user input from the console..
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("What is your name?");
String input = sc.nextLine();
System.out.println("Hi, " + input + ", where are you from");
input = sc.nextLine();
System.out.println("Ohh, " + input + " is nice place I guess!");
System.out.println("and how old are you??");
...
}

It seems that you are mixing up concepts.
Command line arguments are those strings that you see as String[] args parameter to your main method!
But you want the user to provide "more" input to your application, the typical way is to read them from "stdin" (see here to learn how to do that).
Those two are fundamentally different things; and you should first clarify which one you really intend to use (given your example ... probably the "stdin" option).

Try reading the Java IO tutorial here:
https://docs.oracle.com/javase/tutorial/essential/io/cl.html

Related

Java: On the command line, present the user with an editable option [duplicate]

I'm aware of various methods for reading a String from the user's keyboard in Java (Scanner, Console, BufferedReader), however, none of them seems to be capable to accept a given String that the user can edit.
To rephrase it in code, I'm looking for something like this:
Scanner sc = new Scanner(System.in);
System.out.print("Please edit as you like: " + s);
s = sc.nextLine(s);
As this seems so simple, am I overlooking something? Or is this really not possible in Java without a GUI?
Doesn't look like it will be possible. There are similar posts discussing this. Java: populating Scanner with default value on Scanner.nextLine();
A few options have been discussed in there but even the people providing those options are clear that it doesn't meet the stated requirment
If you are trying to edit an existing String, then it's not possible. String is immutable, you can use StringBuilder or create a new String with the new value.

Clarify me how to pass an argument through String args

I start saying that my IDE is eclipse. I was trying to do a program that should find the phone number of a specific person through the name. This is the code
class HelloWorld {
public static void main(String args[]) {
String numbers[][] = {
{"Tom", "555-3322"},
{"Mary", "555-8976"},
{"Jon", "555-1037"},
{"Rachel", "555-1400"},
};
int i;
if(args.length != 1)
System.out.println("Usage: java Phone <name>");
else {
for(i=0; i<numbers.length; i++) {
if(numbers[i][0].equals(args[0])) {
System.out.println(numbers[i][0] + ": " + numbers[i][1]);
break;
}
}
if(i == numbers.length)
System.out.println("Name not found");
}
}
}
I found that in some forums that to make work it I have to go to run -> run configuration -> arguments. Hence I set the program argument to "Mary" and the output was the right one, that showed me the name (Mary) and the phone number (555-8976). Is this the right way or is there a better one?
Your code at present works fine with run-time arguments, as you have seen while using a run-config setup in your IDE. You could also just compile this on the command-line (without an IDE) and then execute java Phone Mary.
If you wish to solicit interactive user input (as opposed to run-time arguments) you would have to refactor using something like Scanner.
The way you are doing the argument passing is fine, but sometimes it's better to ask yourself which is the best option to do something in general, instead of just sticking with an idea and ask how to take that idea in particular to the real world.
To perform this type key-value operation, I recommend using a HashMap. If you don't know about them, that's OK, there are other ways to do what you want. I highly recommend learning about them though, because they make these kind of tasks really easy.
Basically, a HashMap is an object that has values stored in it and to access them you need to specify a key. For example:
Key -------Value
Name: -- "Mary"
Number: "12335635"
Age: -----"64"
Keep in mind all the keys have to be the same type(generally we use String) and the values should also be of the same type, that's why I put the numbers inside quotes. Maybe this example isn't the best one but the key type and the value type doesn't have to be the same. You can have your keys be Strings and your values be int.
I recommend this post: HashMap in Java with Examples and of course, the Java Docs.

Edit a given String over the Console in Java

I'm aware of various methods for reading a String from the user's keyboard in Java (Scanner, Console, BufferedReader), however, none of them seems to be capable to accept a given String that the user can edit.
To rephrase it in code, I'm looking for something like this:
Scanner sc = new Scanner(System.in);
System.out.print("Please edit as you like: " + s);
s = sc.nextLine(s);
As this seems so simple, am I overlooking something? Or is this really not possible in Java without a GUI?
Doesn't look like it will be possible. There are similar posts discussing this. Java: populating Scanner with default value on Scanner.nextLine();
A few options have been discussed in there but even the people providing those options are clear that it doesn't meet the stated requirment
If you are trying to edit an existing String, then it's not possible. String is immutable, you can use StringBuilder or create a new String with the new value.

How to delete previous character printed to console/terminal?

Is there a way to dynamically change output in Java? For instance, in a terminal window if I have:
System.out.print("H")
and then I have:
System.out.print("I")
The output will be:
HI
Is there a way to assign a position to outputs that allows you to replace characters dynamically? For instance (and I know this would not output what I want, I merely want to demonstrate my thinking) this:
System.out.print("H")
Thread.sleep("1")
System.out.print("I")
And it would first print out
H
and then after a second, replace the H with an I?
I'm sure this sounds stupid, I am just interested in dynamically changing content without GUIs. Can someone point me in the direction for this technique? Thank you very much in advance.
You might want to take a look at
System.out.printf
Look at the example shown here: http://masterex.github.com/archive/2011/10/23/java-cli-progress-bar.html
edit:
printf displays formatted strings, which means you can adapt that format and change it for your needs.
for example you could do something like:
String[] planets = {"Mars", "Earth", "Jupiter"};
String format = "\r%s says Hello";
for(String planet : planets) {
System.out.printf(format, planet);
try {
Thread.sleep(1000);
}catch(Exception e) {
//... oh dear
}
}
Using the formatted string syntax found here: http://docs.oracle.com/javase/6/docs/api/java/util/Formatter.html#syntax
As the comment says this solution is only limited to a singular line however dependent on your needs this might be enough.
If you require a solution for the whole screen then a possible solution would be (although quite dirty) would be to hook the operating system using JNA and get a handle on the console window, find its height and then loop println() to "clear" the window then redraw your output.
If you would like to read more then I can answer more questions or here is a link: https://github.com/twall/jna
You can use \b to backspace and erase the previous character.
$ cat T.java
import java.lang.Thread;
public class T {
public static void main(String... args) throws Exception {
System.out.print("H");
System.out.flush();
Thread.sleep(1000);
System.out.print("\bI\n");
System.out.flush();
}
}
$ javac T.java && java T
I
It will output H, then replace it with I after one second.
Sadly, it doesn't work in Eclipse console, but in normal console it does.
This is what you need (uses carriage return '\r' to overwrite the previous output):
System.out.print("H");
Thread.sleep(1000);
System.out.print("\rI");
The C library that is usually used to do this sort of thing is called curses. (Also used from scripting languages that rely on bindings to C libraries, like Python.) You can use a Java binding to it, like JCurses. Google also tells me a pure-Java equivalent is available, called lanterna.

Java Eclipse Taking Command Line Arguments Continously in Running Time

First of all, I read all related topics and none of them answered my question.
I am developing a program in Java using Eclipse and I need to pass some arguments to the program continously after it starts.
For example somehow i need to give it this command by command line after it starts to execute:
CreateTable Students 2 10 10
And then I must be able to give more commands such as :
AddRecord Students Jack 1456
Run Configurations of Eclipse does not solve the problem since I can give arguments to the program only once by using Run Configurations. But I need to do it multiple lines?
Anyone has a solution? Thanks in advance
It doesn't seem to be possible in Eclipse according to this Question (which also lists possible workarounds). Update it's not possible to allocate System.console(), that much is true
But it does work with System.in (thanks Stephen C):
Scanner scanner = new Scanner(System.in);
String line;
while (true) {
System.out.println("Type something please:");
line = scanner.next();
System.out.println(line);
}
Sounds like you should read a sequence of commands from an inputstream, which might be connected to a Scanner (for live input) or a file (for runtime testing.)

Categories