How to read the starting in the command prompt jn Java - java

I am wondering how I can read the starting line from the command prompt in Java.
For example if you run a Java program namned Test.java I usually writes:
java Test
, But if I write this in the command prompt(see below), I would like to read the "string" in the test.java-file when it starts:
java Test string
how can I in the test.java file get access of the string "string"?
I have tried:
Scanner in = new Scanner (System.in);
String text= in.nextLine();
but that only allows me to get access of the next thing that is written in the command prompt.

To read command line parameters you should use the String[] args argument of the main method not read from standard in.

if you are inside main method then you can simply do as
public static void main(String[] args) {
for(int i=0;i<args.length;i++)
System.out.println(args[i]);
}
because args will have all the command line arguments values after java <class name> command

I am guessing that Test class has a main method...
public static void main(String[] args) { ... }
The array passed in to main contains the arguments you pass on the command line...
args[0].equals("string") == true
Or do you want to get the entire command line that started the JVM?

The command line arguments show up in the args[] array that is passed to the main method. So to get the name of the file that was passed on the command line, you can just look at args[0]:
System.out.println(args[0]);

public String nextLine()
Advances this scanner past the current line and returns the input that was skipped. This method returns the rest of the current line, excluding any line separator at the end. The position is set to the beginning of the next line.
Since this method continues to search through the input looking for a line separator, it may buffer all of the input searching for the line to skip if no line separators are present.
Scanner read becomes active when any inputs provided once java program started because of this reason it did not read the command prompt input but it is able to read next line to the command prompt. It did not bother the past input or input provide before scanner class comes into action what it cares the values provided once Scanner class in action.

Related

Java - how can i type in user input using cmd command [duplicate]

This question already has answers here:
How to get input via command line in Java? [closed]
(4 answers)
Closed 1 year ago.
this may be blurry to grasp but i'm new to java whole thing and i want to know how can i use cmd to type something in user input
E:\My apps\Java apps\test\src\main\java>java ls.java && echo E:/
enter File name or path :
in this input i want to enter the path via cmd the "&& echo E:/" doesn't work
You can use "Command Line Arguments" in order to give the input when running the program!
Assuming your file name is ls.java
compile it using: javac ls.java
when running it using java command type the arguments in front of it like:
java ls E:/path
Now you can catch the arguments in the program
public class ls {
public static void main(String[] args)
{
String path = args[0];
}
}
you can add more arguments by spaces and catch them in String array
java ls E:/path 100 200
System.out.println(args[1]); // will print 1
System.out.println(args[2]; //will print 200
NOTE: As implied all the command line arguments are stored in the form of String, if you want to convert them to another format, you'd need to parse them using methods.

Java user console input on sublime text 3 not working

I am trying to get the user to enter their name and have it be printed out on java using Sublime Text 3. After the user enters their name when a message prompts them for it, their name is supposed to be printed out but it justs skips over to a new blank line. It works on online compilers but not on Sublime. How do I get user console input to work on Java Sublime Text 3?
import java.util.Scanner;
public class SocSecProcessor {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter name: ");
String name = input.nextLine();
input.close();
System.out.println(name);
}
}
You have to launch execution in a separate console, not the sublime text pseudo console.
The solution is to launch with START command in a batch file .bat
for example:
START CMD /K %RELATIVE_PATH%\jdk\bin\java -cp %~dp1 %~n1
where %1 is the file class with main method. Go to the batch syntax documentation if necessary... Your build system in sublime must launch a batch file with this kind of
instruction.

Java code fails to parse command line arguments pass from wrapper script

I have pretty simple wrapper script which aquires parameters and passes them to java jar.
Unfortunatly, I experience very-very strange behaviour. Below is an example.
Command to execute script:
./wrapper http://localhost:8485/metrics 900 200
Script:
#/bin/sh
/usr/java/default/bin/java -jar /usr/plugins/checkmetrics.jar $#
Java code:
public static void main(String[] args) throws IOException {
String metricsUrl = args[0];
int heapWarnValue = Integer.parseInt(args[1]);
int threadWarnValue = Integer.parseInt(args[2]);
}
Which gives me NumberFormatException:
"xception in thread "main" java.lang.NumberFormatException: For input string: "200
But if I change command to following, everything works:
./wrapper http://localhost:8485/metrics 900 200" "
Breaks my brain, but I can't understand where I'm wrong. Could someone explain?
Thanks in advance
Is there an LF or CR character at the end of the script that is not being correctly processed (could happen if you have unix line endings in a windows environment or vice versa)?
the reason I mention this is that the error you mention says that it is
For input string: "200
I'm willing to bet that there is another quote mark at the start of the next line. If that's the case, it's trying to parse 200 and CR together as an integer. Sort out the line endings and all will be fine.

Why does System.console() return null for a command line app? [duplicate]

This question already has answers here:
System.console() returns null
(13 answers)
Closed 8 years ago.
I am working on a legacy app which depends on user command line input:
String key = System.console().readLine("Please enter the license key: ");
However, I am getting a NullPointerException because System.console() gives me a null.
Why does System.console() return null for a command line app? It happens when running it out of the terminal as well as IDE.
If you start java from a terminal window, then it really should work, even though I haven't tried on OSX.
If you run a simple test using java directly from the terminal, does it work?
echo 'public class Test { public static void main(String[] args) {System.console().printf("hello world%n");}}' >Test.java && javac Test.java && java Test
Expected output:
hello world
If it doesn't work, then sorry, no console support on your platform.
However, if it works, and your program doesn't then there is a problem with how your program is started.
Check how the java binary started? Is it started from a shell script? Check that stdin/stdout have not been redirected or piped into something, and possibly also that it's not started in the background.
ex: This will probably make System.console() return null.
java Test | tee >app.log
and this:
java Test >/tmp/test.log
This seems to work on my machine (linux)
java Test &
Neither does it seem as if System.setOut, System.setErr or System.setIn affects the console, even after a couple of gc's and finalizers.
However:
Closing (the original) System.out or System.in will disable the console too.
echo 'public class Test { public static void main(String[] args) {System.out.close();System.console().printf("hello world%n");}}' >Test.java && javac Test.java && java Test
Expected output:
Exception in thread "main" java.lang.NullPointerException
at Test.main(Test.java:1)
So; scan your code for places where it closes streams, or passes System.out somewhere it might get closed.
To read from Standard input (command line input) you must use some kind of stream reader to read the System.in stream.
An InputStreamReader initialised by
InputStreamReader(System.in)
lets you read character by character.
However, I suggest wrapping this with a BufferedReader:
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
String inputLine = reader.readLine();
Must import
java.io.*;

giving special characters at command line arguments

Hi all! I have written this program for reading command line arguments.
public class UseArgument {
public static void main(String args[])
{
System.out.print("hi, ");
System.out.print(args[0]);
System.out.println(" How are you?");
}
}
I tried to send the following argument through the command line:
java UseArgument #!&^%
and it's throwing an error as follows.
Output:
hi, #! How are you?
''%'' is not recognized as an internal or external command,
operable program or batch file.
java UseArgument #!^%
Can anybody explain this behavior? Does this relate to regular expressions?
Thanks.
sivakiran B
Some of the special characters you are using have a meaning to the shell from which you are launching your program. By putting the characters in quotes, you are instructing the shell not to process these characters according to their special meaning.

Categories