简体   繁体   中英

How can I pass variables from the command prompt into my java program

Is there a way to read data from the command prompt? I have a java program that relies on 4 input variables from an outside source. These variables are returned to the command prompt after I run a javascript program but i need a way to pass these variables from the command prompt into my java program, any help would be greatly appreciated!

While executing java program pass the parameters and all the parameters should be separated by space.

java programName parameter1 parameter2 parameter3 parameter4

This parameters would be available in your main method argument

 public static void main(String[] args){
     //This args array would be containing all four values, i.e. its length would be 4 and you easily iterate values.
    for(int i=0; i<args.length; i++){
        System.out.println("Argument " + i + " is " + args[i]);

}

Follow the link:

Command-Line Arguments - The Java™ Tutorials : https://docs.oracle.com/javase/tutorial/essential/environment/cmdLineArgs.html

shared by @BackSlash.

It has all the content which would help you to clear all your doubts.
The content from the link is quoted below:

Displaying Command-Line Arguments passed by user from command-line to a Java program

The following example displays each of its command-line arguments on a line by itself:

 public class DisplayCommandLineParameters { public static void main (String[] args) { for (String s: args) { System.out.println(s); } } }

To compile the program: From the Command Prompt, navigate to the directory containing your .java file, say C:\test, by typing the cd command below.

C:\Users\username> cd c:\test
C:\test>

Assuming the file, say DisplayCommandLineParameters.java, is in the current working directory, type the javac command below to compile it.

C:\test> javac DisplayCommandLineParameters.java
C:\test>

If everything went well, you should see no error messages.

To run the program: The following example shows how a user might run the class.

C:\test> java DisplayCommandLineParameters Hello Java World

Output:
Hello
Java
World

Note that the application displays each word — Hello, Java and World — on a line by itself. This is because the space character separates command-line arguments.

To have Hello, Java and World interpreted as a single argument, the user would join them by enclosing them within quotation marks.

C:\test> java DisplayCommandLineParameters "Hello Java World"

Output: Hello Java World

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM