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.)
Related
The standard JVM method for reading a password from the command line without showing it is java.io.Console.readPassword(). This, however, shows nothing while the user is typing; users accustomed to graphical programs will expect symbols such as "•" or "*" to appear in place of the characters they type. Naturally, they will also want backspacing, inserting, and so on to work as normal, just with all the characters being operated on replaced with the same symbol.
In 2019, is there a generally accepted JVM procedure for showing "*******" when the user types "hunter2" in a console application? Can this even be done properly without a GUI? A 2011 SO question on the topic got an answer linking to this article on the topic; can we do better nowadays than the rather elaborate solution shown therein?
(I happen to be using Kotlin as my language of choice, so a Kotlin-specific solution will satisfy if there is one.)
hunter2? Wow. Reference acknowledged.
There is no easy way. The primary problem is that the standard System.in doesn't give you any characters at all until the user has pressed enter, so there's no way to emulate it (if you try to read char-for-char from System.in and emit a * every time a key is pressed, that won't work).
The lanterna library at https://github.com/mabe02/lanterna can do it, though. If you want to emulate it, it's.. very complicated. It has branching code paths for unix and windows. For example, on unix, it uses some hackery to figure out what tty you're on, and then opens the right /dev/tty device. With lanterna, writing this yourself would be trivial.
It's that or accept Console.readPassword()'s blank nothingness, really. Or, write a web interface or a swing/awt/javafx GUI.
I think answer to your question can be found here in stackoverflow itself.
please see this:
masking-password-input-from-the-console-java
sample code from there:
import java.io.Console;
public class Main {
public void passwordExample() {
Console console = System.console();
if (console == null) {
System.out.println("Couldn't get Console instance");
System.exit(0);
}
console.printf("Testing password%n");
char passwordArray[] = console.readPassword("Enter your secret password: ");
console.printf("Password entered was: %s%n", new String(passwordArray));
}
public static void main(String[] args) {
new Main().passwordExample();
}
}
hope this is helpful. :)
How would you reprint a line after taking an input from the user (from terminal)?
I realise that you could reprint a line using:
System.out.print("\r foo");
System.out.print("\r bar");
Which will produce the output:
bar
but once you take an input from the user, this doesn't seem to work. For instance:
System.out.print("\r foo");
Scanner sc = new Scanner(System.in);
int i = sc.nextInt();
System.out.print("\r bar");
If you type in 1 as the input, you get:
foo1
bar
Can you reprint on the same line as foo (or more specifically, foo1) once the user has provided an input?
The key here is likely to be "raw" vs "cooked" mode of input. To do what you want, you will need to use "raw" mode where you collect each character as it is typed, and decide what to do with it, including whether you echo it to the console or not.
Cooked mode is more common for simple command line program input, and basically means "Give me the user's input, one line at a time". And "one line at a time" generally translates to "when the user presses enter." Most "cooked" implementations echo the keyboard input to the console.
For a host of reasons, doing "raw" mode in CLI programs is difficult -- not impossible, but difficult. I will spare the details in this venue (which are numerous and do not lend themselves to easy copy and paste here), and instead point you to the resource I used when attempting the same a few years ago:
Non blocking console input in Python and Java
A quick hunteke summary: the terminal/console needs to change state, not just your program, and there is no portable method for doing so. You'll be outsourcing to other libraries or programs to do what you want -- just don't forget to undo it when your program quits, or your users won't be happy!
package happy;
import java.util.Scanner;
public class PiVal {
public static void main(String[] args)
{
Scanner s = new Scanner(System.in); //initialise scanner
String val= Double.toString(Math.PI); //Storing PI to string
System.out.println(val);//Printing the stored value
System.out.println("Enter the value");//Screen output to print
int till =s.nextInt(); //taking user input storing in till
till+=2; //increasing value to +2 as only want to change after decima
if(till>15) //Checking if variable value more than 15
{
System.out.println("Out of bounds");
}
System.out.println(val.substring(0,till));
s.close();
}
}
My code looks like this very simple code i know just revising some stuffs but the thing i am not able to get my head around is why i need to input 2 times just to run the code and the "Print " command is not running very first it is running after the scanner input.
OutPut looks like this
8
8
3.141592653589793
Enter the value
3.14159265
Edit:
Eclipse LUNA
Seeing that the code produces the correct output for everyone else, there is something wrong with your IDE. Try running your program in another IDE and see if that helps. You should update Eclipse Luna(if any updates are available) and restart it(just quit and reopen). That should solve your issue, however if it does not, You may need to use a different Environment.
Refer to this link dude. It's always recommended by the developer of eclipse to use the most updated version of eclipse. But of course, it's not necessary all the time. However, luna is using version 4.4, while the second latest eclipse is already using 4.6 which is ahead by at least 2-3 years.
What you're facing could be some issues that no one really has officially brought up before. It's just how certain IDE works behind which programmers like us may not understand. It's similar to Quincy who doesn't follow the correct order during program runtime.
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
This has been asked before, but was not clarified to the point where I get it. Similar to the one or two other threads I've seen on this subject, I'm working on a chat client with command line inputs for logging in/off, disconnecting, etc. and I am unsure how to simulate this in a JUnit test case. Other responses indicated that I should try changing the System.in to a separate InputStream but...then what?
tl;dr: I have a method in my actual code for parsing command line input, and need a JUnit way of testing that these were entered and appropriately processed.
EDIT: It seems I misunderstood the question. I usually use the term "command line input" to refer to command line arguments given to the process to start with, rather than interactive console input. However...
Handing your real code either a different InputStream or possibly even a Reader or Scanner would indeed help - anything to separate the "getting input" part from the console. You can then fake the input all in one go pretty easily, using a String as input in your test code, and then either converting it to bytes and wrapping those bytes in a ByteArrayInputStream or wrapping the string directly in StringReader.
The downside of this is that there's no easy way of making this "pause" after one command in order to check the results.
You may want to alter the design somewhat so that the part which reads the input is separated from the part which handles the input. The reading part could be a very simple loop, on the order of:
String line;
while ((line = reader.readLine()) != null) {
handleInput(line);
}
You could then potentially leave that part untested by unit tests, or write some relatively primitive tests - but you can then test handleInput extensively, as it's now separated from the input source.
Original answer
If you've extracted the parsing code from the code which really starts the application, it's easy: run that code, and check the results. This will be easiest if you have some sort of class encapsulating the options, of course. For example, your main method might look like this:
public static void main(String[] args) {
Options options = Options.parse(args);
// Use options here
}
Then you can just test Options.parse very easily.