I have a class that contains the following main method:
public static void main(String[] args) {
System.out.println("args.length: " + args.length);
if (args.length == 1) {
// do something
} else if (args.length == 2){
// do something
}
... Some code ...
}
The problem is that the arguments in command line are not read.
When I type ./program arg1 Arg 2 .... I always get args.length equals to 0. I tried to verify the length of arguments in other classes and I got the correct number
What could be the problem ?
Assuming program is a script, it should look like this :
#!/bin/sh
java foo.bar.YourClass "$#"
It should now work with arguments
./program is a script.
In fact, I forgot to add $* at the end of " java -cp <...> myclass ". So, it was normal not to take into account the command line arguments.
Thanks for all of you !
Related
This question already has an answer here:
What does "error: '.class' expected" mean and how do I fix it
(1 answer)
Closed 11 months ago.
I don't know why this cannot run, the error on "num = Integer.parseInt (args[]) ;"
class CommandLine {
public static void main (String args [])
{
int num ;
num = Integer.parseInt (args[]) ;
if (num>=100)
{
} else {
System.out.println("Number is less than 100");
}
}
}
In order to use args[], you need to pass a command-line argument when you run the class. For example, if you are running from command prompt, you will need to do something like this:
java CommandLine 100
In your code, you could do something like this
class CommandLine {
public static void main (String args[]) {
int num = Integer.parseInt (args[0]) ;
if (num>=100)
{
System.out.println("You entered ");
} else {
System.out.println("Number is less than 100");
}
}
}
Which will result in displaying You entered 100 on the console. If you are running from an IDE like Eclipse, you will need to set up the command-line argument through the "Run Configurations" menu. Then, you enter (space-separated) arguments in the "Program arguments" text area.
In IntelliJ, you do the same through the "Modify run configuration" menu
The argument array args[] in a class' main method is built by the JVM. It is a string of command-line arguments that are passed to the executed class. The JVM parses out the command line instruction and will gather any and all values after the class name and will create that args array. If you pass nothing to the program, then the array will be empty.
An command-line instruction like
java MyClass Hello World Welcome to Java
builds a String array with 5 values.
I basically want to store my user input in an array of size 3. When I seem to put 3 in the main (String [3] args), it doesn't seem to do what I want. How do I resolve this issue?
If it helps, the exercise is asking me to: Fill in the class method main of class Ex4 with code that
create an array of size 3 containing strings and fills it with command line arguments.
Thanks.
public class Ex4 {
public static void main(String[] args)
{
if (args.length == 1)
{
System.out.println(args[0]);
}
else if (args.length == 2 || args.length == 3)
{
System.out.println(args[0]);
System.out.println(args[1]);
}
else
System.out.println("Too many arguments");
}
}
You can't control the size of the array passed to the main method. It will automatically be allocated with the size of the arguments passed to the program.
You get it backwards.
You define the size of that array implicitly, by the number of arguments that you pass when starting the JVM.
At runtime, within your Java code you can only check the actual length of that array. For example to give an error message to the user telling him about the required number of arguments and their meaning.
import javax.swing.JOptionPane;
public class Cortana2 {
public static void main(String[] args) throws Exception {
//Declaring Variables (Add more commands)
String command;
// Command will always stay the same
// All strings below are commands to put in
String Steam;
String League;
League=("League");
Steam=("Steam");
command= JOptionPane.showInputDialog("Give a valid command");
if (command == null) {
JOptionPane.showMessageDialog(null, "This is not a valid command. If you have forgotten what commands are valid, please refer to Devon for assistance");
JOptionPane.getRootFrame().dispose();
} else if (command == League) {
Runtime.getRuntime().exec("\"D:/LeagueClient.exe\"");
} else if (command == Steam) {
Runtime.getRuntime().exec("\"C:/Program Files (x86)/Steam/Steam.exe\"");
}
}
}
Not 100% sure why I'm getting the error. I've seen where others said to remove the semicolons from the 'if' statements but then nothing executes when I run the program and type in commands. Sorry if anything seems poorly formatted.
if (command == null);
Don't put a ";" at the end of your if/else statements.
but then nothing executes when I run the program and type in commands
Don't use == to compare String.
Instead use the String.equals(...) method
Also variable names should NOT start with an upper case character.
You have an extraneous semicolon at the end of each test
else if (command == League); // <- remove these semicolons
You're also going to have grief using == to compare strings. Use .equals() instead.
Remove Semicolon From If, Else If An Use equals Method After Your Code Looks Like This..
command= JOptionPane.showInputDialog("Give a valid command")
{
if (command.equals(null)
{
JOptionPane.showMessageDialog(null, "This is not a valid command. If you have forgotten what commands are valid, please refer to Devon for assistance");
JOptionPane.getRootFrame().dispose();
}else if (command.equals(League))
{
Runtime.getRuntime().exec("\"D:/LeagueClient.exe\"");
}else if (command.equals(Steam))
{
Runtime.getRuntime().exec("\"C:/Program Files (x86)/Steam/Steam.exe\"");
}
System.exit(0);
}
I'm a Java beginner and I'm confused about testing args.length at the begining of many codes, and why it's never gets higher than 0 in any of my codes?
import java.net.Socket;
import java.net.UnknownHostException;
import java.io.IOException;
public class LowPortScanner {
public static void main(String[] args) {
String host = "localhost";
if (args.length > 0) {
host = args[0];
}
for (int i = 1; i < 1024; i++) {
try {
Socket s = new Socket(host, i);
System.out.println("There is a server on port " + i + " of "
+ host);
}
catch (UnknownHostException ex) {
System.err.println(ex);
break;
}
catch (IOException ex) {}
} // end for
} // end main
} // end PortScanner
You have to inputs to main mathod from Command prompt.
like below
java LowPortScanner TEST1 TEST2
Because if it is not tested then an exception would be thrown because host = args[0]; would illegal.
However, this doesn't look like it's going to help much, an empty or null host looks like it would cause further problems.
If the length of args is always 0, then be sure you're actually passing in parameter arguments.
If there are no command arguments the args[0] will fail. This is why it must be protected.
It depends on how you invoke the Java class file. In command prompt or bash shell:
java LowPortScanner Argument1
typing the above line in the command prompt/bash will cause the argument count to increase to 1. (because Argument1 is one argument, after the class file LowPortScanner)
java LowPortScanner Argument1 Argument2
the above line will make argument count to increase to 2.
hence args.length will be 2 in the second case and 1 in the first case.
If you are calling your program from CMD or bash you can asign ARGuments it like
java LowPortScanner google.com
Then "google.com" is your args[0]. When your program supports commandline attributes it is recommended to test if the given arguments are corret.
The variable String[] args hold all the parameter pass to the program thorough command line if you are not passing any argument then the length of args become 0. Now it's better to check it's length before accessing it other wise there is chance to get ArrayIndexOutOfBoundsException if it's size is 0
args in public static void main(String[] args is the String array of arguments passed from command line.
java LowPortScanner argument1 argument2
if you try the above command args.length will return 2.
As far as question of checking the length it is done for java programs which can take command line arguments and if arguments are not passed then they prompt for input.
if(args.length >0 ){
//proceed using passed arguments
}else{
//proceed with some default value
}
You are running your program using java LowPortScanner hence no arguments are passed and args.length is always zero.
Moreover if you don't pass any argument and use host=args[0] you will get ArrayIndexOutOfBoundsException.
How do I pick the methods in my program to run using command line arguments? For example, if I want my program to process an image called Moon.jpg, how do I make it work so that -S Moon.jpg in the command line would invoke the Scale method? Or -HI Moon.jpg would flip the image Horizontally and Invert it? I have some methods written and they work when I run the program normally.
You can parse arguments with a function like this:
private void parseArguments(String[] args)
{
int i = 0;
String curArg;
while (i < args.length && args[i].startsWith("-"))
{
curArg = args[i++];
if ("-S".compareTo(curArg) == 0)
{
if (i < args.length)
{
String image = args[i++];
processImage()
}
else
{
// ERROR
}
}
}
}
Your main method should always have String[] args which contains arguments split on the space character. There are also plenty of libraries you can use to parse command line arguments. This method is quite similar to what the Apaches CLI library uses (Of course there's a lot more that comes with that library but the parser uses this logic).
http://commons.apache.org/cli/
This should help. and here's how to use it:
http://commons.apache.org/cli/usage.html
You may need to write different methods for each purpose and have if/else conditions based on command input.
why not read the arguments passed and read subsequent value to do the required stuff
ie,
java yourprogram -a1 something -a2 somethingelse
and in your program
public static void main(String[] args){
for(int i=0;i<args.length;i++){
switch(args[i]){//you can use if-else to deal with string...
case "-a1":read args[i+1] to get value to do somethng
case "-a2": read args[i+1] to get value to do something else
}
}