I pass command line arguments to my java code in eclipse (and retrieve it using args[] in main method)-this is fine.
However, my scenario is different. My code periodically asks for input during execution. Where would I enter such input? when controls hits such input prompt, eclipse freezes
EDIT
Some of the answers I read below suggests using command line args or buffered reader or using console view: but my eclipse freezes right after asking me for sudo password (further, my situation is different from command line args as explained in the very first line).
I am using Kepler on centos 6.5
Eclipse has a console, its typically located at the bottom of your java perspective. If its not there just go to Window->Show View->Console.
Have you ever used an input stream reader or a buffered reader?
The following is a start on how
static InputStreamReader input = new InputStreamReader(System.in);
static BufferedReader in = new BufferedReader(input);
Then you can use the buffered reader for taking input during execution.
you can pass command line arguments from eclipse, run your program from eclipse as run on configuration it will open dialog box and click arguments tab and pass your arguments from there
Go to Window -> Show View -> Console. You will able to enter input.
For short cut , type : Alt + Shift + Q, C.
Use the Scanner class. You have to import it from java.util.Scanner;
String userInput;
Scanner input = new Scanner(System.in);
System.out.print("Enter something: ");
userInput = input.nextLine();
and remember to close the scanner when you're done using it
input.close();
Puzzled why my question is down voted and why few respondents suggested irrelevant answer.
You can pass input using scanner or input stream if your code is expecting it. But my question is asking for uncertain situations(in this case, if my eclipse is started as sudo it wont ask for root password; but if I start as regular user it would ask for root password based on the Linux shell command that my java code has to exec)
Yes, you can pass the input to java code (executed under eclipse). From the command line window where eclipse was started, we can enter the input and java code can read it as string.
Related
I found codes getting input as command line arguments.I am using Eclipse but the example code in Algorithms 4th Edition accepts args[0] and so on.I knew we can input argument in Eclipse.
Edit starts
In Eclipse,I need to go to the Run Configuration in order to enter the argument when there is a line of code like this int T = Integer.parseInt(args[0]);
But it's obvious that if we write the codeint T = scanner.nextInt();
I don't even need to go to Run Configurationto enter the Program Arguments and all I need is just click the run button and input the value in the console of Eclipse.
Edit ends.
So,My question is:
1)What is the function(s) for using command line arguments when we can solve the problem using Scanner class?
Thanks for any explanations!
That is just an another way of doing things. Sometimes command line arguments are useful for quickly checking how your program responds with different inputs. I guess you just started your programming journey and that is why you are asking question like this.
And let me tell you there is a difference between argument and input. Scanner class helps you to take input from the console whereas command line arguments are passed as an argument to your main function.
Here are some advantages of using command line arguments.
You can pass any number of arguments and you do not need to define variables for them.
The next benefit is you can pass any data type with command line and then you can code your functions accordingly.
And the final answer for you, don't think about why this when we already have this. It is programming and you should learn as much as you can. You will find 1000s ways of doing the same thing. So enjoy learning.
When you compile your code, you execute javac MyClass.java
When you run the code, you execute java MyClass.
Well, MyClass.java is a command line argument to the javac command, and MyClass is a command line argument to the java command.
Do you think those commands would be better if they instead stopped and asked for the values they need? Especially considering there are a lot of options that can be set, so should they ask for each option, one at a time, so you'd have to press Enter 20+ times before the compilation started?
That is just 2 examples for command-line arguments, and how useful they can be.
Let's use another example. We want to create a Zip file, which at its simplest need a name for the Zip file, and a list of file names to add to the Zip file.
Using Scanner, that might look like this:
java CreateZip
Enter name of Zip file: foo.zip
Enter name of file to include, blank when done: Hello.txt
Enter name of file to include, blank when done: Yeehaa.txt
Enter name of file to include, blank when done: bar.doc
Enter name of file to include, blank when done: baz.png
Enter name of file to include, blank when done:
Zip file created
Or you could use command-line arguments:
java CreateZip foo.zip Hello.txt Yeehaa.txt bar.doc baz.png
Zip file created
Which approach is better? What if you want to do that from a script? How can the script answer questions?
I have just started learning Java with IntelliJ IDE. I know a bit C# so the logic makes some sense, however there is one thing so far I couldn't get over it.
How do I read from the console? In C#, you could easily read what the human typed into it, using Console.ReadLine(). In Java, System.console().readLine(); does not work for me and throws a NullPointerException.
What am I missing here?
NOTE: problem doesn't appear when we run your code from console/terminal via java [options] [MainClass] so if this is valid solution for you you can stop reading here. Rest of this answer is for people who are using some IDEs to run their code.
Problem
Most IDEs are using javaw.exe instead of java.exe to run Java code (see image below).
Difference between these two programs is that javaw runs Java code without association with current terminal/console (which is useful for GUI applications), and since there is no associated console window System.console() returns null. Because of that System.console().readLine() ends up as null.readLine() which throws NullPointerException since null doesn't have readLine() method (nor any method/field).
But just because there is no associated console, it doesn't mean that we can't communicate with javaw process. This process still supports standard input/output/error streams, so IDEs process (and via it also we) can use them via System.in, System.out and System.err.
This way IDEs can have some tab/window and let it simulate console.
For instance when we run code like in Eclipse:
package com.stackoverflow;
public class Demo {
public static void main(String[] args) throws Exception {
System.out.println("hello world");
System.out.println(System.console());
}
}
we will see as result
which shows that despite javaw.exe not having associated console (null at the end) IDE was able to handle data from standard output of the javaw process System.out.println("hello world"); and show hello world.
General solution
To let user pass information to process use standard input stream (System.in). But since in is simple InputStream and Streams are meant to handle binary data it doesn't have methods which would let it easily and properly read data as text (especially if encoding can be involved). That is why Readers and Writers ware added to Java.
So to make life easier and let application read data from user as text you can wrap this stream in one of the Readers like BufferedReader which will let you read entire line with readLine() method. Unfortunately this class doesn't accept Streams but Readers, so we need some kind of adapter which will simulate Reader and be able to translate bytes to text. But that is why InputStreamReader exists.
So code which would let application read data from input stream could look like
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.print("Hello. Please write your name: ");
String name = br.readLine();
System.out.println("Your name is: "+name);
Preferred/simplest solution - Scanner
To avoid this magic involving converting Stream to Reader you can use Scanner class, which is meant to read data as text from Streams and Readers.
This means you can simply use
Scanner scanner = new Scanner(System.in);
//...
String name = scanner.nextLine();
to read data from user (which will be send by console simulated by IDE using standard input stream).
If you realy need to Console object you can compile your class from command line. Firstly in my java file first statement is package com.inputOutput;
Go in your project "src" folder and compile it like : "javac com/inputOutput/Password.java" 'com' and 'inputOutput' are folder(package). Run your class file in src folder
java com.inputOutput.Password". It had worked work for me.
You could use an Jframe.
JFrame frame = new JFrame("titile");
// prompt the user to enter their code
String code = JOptionPane.showInputDialog(frame, "promt here");
java.util.Scanner API is what you are looking for.
I have just started learning Java with IntelliJ IDE. I know a bit C# so the logic makes some sense, however there is one thing so far I couldn't get over it.
How do I read from the console? In C#, you could easily read what the human typed into it, using Console.ReadLine(). In Java, System.console().readLine(); does not work for me and throws a NullPointerException.
What am I missing here?
NOTE: problem doesn't appear when we run your code from console/terminal via java [options] [MainClass] so if this is valid solution for you you can stop reading here. Rest of this answer is for people who are using some IDEs to run their code.
Problem
Most IDEs are using javaw.exe instead of java.exe to run Java code (see image below).
Difference between these two programs is that javaw runs Java code without association with current terminal/console (which is useful for GUI applications), and since there is no associated console window System.console() returns null. Because of that System.console().readLine() ends up as null.readLine() which throws NullPointerException since null doesn't have readLine() method (nor any method/field).
But just because there is no associated console, it doesn't mean that we can't communicate with javaw process. This process still supports standard input/output/error streams, so IDEs process (and via it also we) can use them via System.in, System.out and System.err.
This way IDEs can have some tab/window and let it simulate console.
For instance when we run code like in Eclipse:
package com.stackoverflow;
public class Demo {
public static void main(String[] args) throws Exception {
System.out.println("hello world");
System.out.println(System.console());
}
}
we will see as result
which shows that despite javaw.exe not having associated console (null at the end) IDE was able to handle data from standard output of the javaw process System.out.println("hello world"); and show hello world.
General solution
To let user pass information to process use standard input stream (System.in). But since in is simple InputStream and Streams are meant to handle binary data it doesn't have methods which would let it easily and properly read data as text (especially if encoding can be involved). That is why Readers and Writers ware added to Java.
So to make life easier and let application read data from user as text you can wrap this stream in one of the Readers like BufferedReader which will let you read entire line with readLine() method. Unfortunately this class doesn't accept Streams but Readers, so we need some kind of adapter which will simulate Reader and be able to translate bytes to text. But that is why InputStreamReader exists.
So code which would let application read data from input stream could look like
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.print("Hello. Please write your name: ");
String name = br.readLine();
System.out.println("Your name is: "+name);
Preferred/simplest solution - Scanner
To avoid this magic involving converting Stream to Reader you can use Scanner class, which is meant to read data as text from Streams and Readers.
This means you can simply use
Scanner scanner = new Scanner(System.in);
//...
String name = scanner.nextLine();
to read data from user (which will be send by console simulated by IDE using standard input stream).
If you realy need to Console object you can compile your class from command line. Firstly in my java file first statement is package com.inputOutput;
Go in your project "src" folder and compile it like : "javac com/inputOutput/Password.java" 'com' and 'inputOutput' are folder(package). Run your class file in src folder
java com.inputOutput.Password". It had worked work for me.
You could use an Jframe.
JFrame frame = new JFrame("titile");
// prompt the user to enter their code
String code = JOptionPane.showInputDialog(frame, "promt here");
java.util.Scanner API is what you are looking for.
I am adding a command line interface to a Java program. It receives arguments on the command line and some input from the keyboard. It displays a text message to prompt for each of the necessary keyboard inputs.
If someone redirects the System.in from a file, the display text should be suppressed.
My first approach is to run the following check at startup:
System.in.available() > 0
Is this reliable or is there a better way of distinction?
When using a Scanner object is it possible to ensure the cursor always focuses in the console? For example when I run my program if I do not click in the console and start typing my input ends up in the middle of my program code if I am not paying attention.
Scanner s = new Scanner(System.in);
String name = s.nextLine();
System.out.print("Enter your name")
So when I run this program I will get Enter your name in the console and I would like to automatically focus the cursor ready to take users info at the end of the sentance.
Thanks for any help
No, it's not possible, at least not in general. Scanner has absolutely nothing to do with the console (it might be reading input from a socket or a file) and even if it is reading from the console, it cannot control your cursor location.
Something like java.awt.Robot would give you limited ability to control the cursor (via mouse clicks) but it would be very environment specific (what if the user moves the console? what if they're not even running in the IDE/from the command line?)
You're solving a problem that you don't need to solve, and at a level that shouldn't be cognizant of the problem (if anything, solve this in environment configuration, not in program logic).
As AKJ said, not focusing on the console, totally depends on IDE.
As for your code, it will first wait for the user input then user is prompted. Hence, you might interchange the second and third line of code.
Scanner s = new Scanner(System.in);
System.out.print("Enter your name");
String name = s.nextLine();