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.
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 have a java program that takes command line arguments and then converts the decimal value to its hexadecimal counterpart. I am trying to make use of an exception handling code block (try/catch) which is not being triggered. The try/catch block is intended to be triggered when no command line arguments are passed to the program.
Have ran program through Jenkins/SonarQube to identify code smells and remedy issues. Have utilised process of trial and error, to experiment with different possibilities to see if I can resolve the design flaw.
https://pastebin.com/frBq46zs
//import java.util.Scanner;
public class Dec2Hex
{
public static int Arg1;
public static void main(String args[])
{
Scanner scan = new Scanner(System.in);
System.out.println("Enter any number: ");
//Arg1= scan.nextInt();
//scan.close();
if (args.length < 0)
{
try
{
Arg1 = Integer.parseInt(args[0]);
}
catch (NumberFormatException e)
{
System.err.println("Argument" + args[0] + " must be an integer.");
System.exit(1);
}
}
Utilising if (args.length > 0) with no command line value results in the exception not being triggered. I thought that this was to be expected, because the exception block would never be triggered because the conditional statement has not been satisfied.
However, the converse was not as expected. I thought that if (args.length==0) then this would mean "no arguments have been passed, attempt to parse the value entered, at the command line. If still despite that, no value can be parsed, THEN trigger the catch statement generating the error message and output it to the user."
Whenever I use args.length==0 or args.length<0 with no command line arguments submitted, all I get is a:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 0 out of bounds for length 0
Message which specifically refers to the following line of code:
Arg1 = Integer.parseInt(args[0]);
In your code Arg1 = Integer.parseInt(args[0]); before method call Integer.parseInt method arguments will be resolved. So it will try to get first element from argument list (as Java array is 0 based it will get first element with index 0).
As you are not passing any command line argument, code is breaking during argument resolution. Because the array length is 0, args[0] is giving ArrayIndexOutOfBoundsException. Which is an expected scenario. So you should case this exception as well.
try
{
Arg1 = Integer.parseInt(args[0]);
}
catch (ArrayIndexOutOfBoundsException e)
{
System.err.println("No Argument Provided.");
System.exit(1);
}
catch (NumberFormatException e)
{
System.err.println("Argument" + args[0] + " must be an integer.");
System.exit(1);
}
And you don't need that if condition of checking for argument length, if you want to execute the exception code for 0 length. If you want to execute existing exception block pass argument that is not a number and remove the if condition.
In summary, code will reach to NumberFormatException block when you pass some argument and that is not a number. And that exception will be thrown by Integer.parseInt. And current exception is being thrown by args[0] because array length is 0 and you are trying to retrieve the first array element from empty array and it's throwing ArrayIndexOutOfBoundsException.
Although it's not desirable to reach to exception code, while you can handle that even before that.
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 !
This question already has answers here:
What Exacly (args.length>0) means?
(6 answers)
Closed 8 years ago.
recently i've come across this piece of code and i really want to understand when and how to use this args.length
import java.util.*;
class Average
{
public static void main(String args[])
{
Scanner sc = new Scanner(System.in);
int choice;
int a=0,min=0,max=0,x;
int n = args.length;
System.out.println("1-Sum");
System.out.println("2-Average");
System.out.println("3-Minimum");
System.out.println("4-Maximum");
System.out.println("enter your choice");
choice = sc.nextInt();
for(int i=0;i<n;i++)
{
a+=Integer.parseInt(args[i]);
}
switch(choice)
{
case 1: System.out.println("The sum is :" +a/n);
break
case 2: System.out.println("The Average is :" +a/n);
break
case 3: for(int i=0;i<n-1;i++)
{
x=Integer.parseInt(args[i]);
if(x<Integer.parseInt(args[i+1]))
min=x;
else min=Integer.parseInt(args[i+1]);
}
System.out.println("The minimum is :" +min);
break;
case 4: for(int i=0;i<n-1;i++)
{
x=Integer.parseInt(args[i]);
if(x>Integer.parseInt(args[i+1]))
max = x;
else max=Integer.parseInt(args[i+1]);
}
System.out.println("The maximum is :" +max);
break;
}
}
}
The main() method is initial point where java program execution starts. That's why the main() method is public, static and void. The parameters passed to main() method are String args[] i.e a String array. It is not necessarily the variable name can be only args, it can be any variable name i.e String names[].
Now, why args.length is zero, when no arguments passed:
When any java program is run from command line, it is run as java ProgName.
The command line arguments are passed to java program as java ProgName Arg1 Arg2.
Here in this example, two arguments are passed to java program ProgName. It is simple that, the arguments are passed to java program is the same way we run a command with parameters on any operating system. The arguments are passed along with command just by separator character as "space".
Java Interpreter interprets these arguments and pass to main() method of java program.
When we pass arguments to java program from command line it is stored in the args[] String Array. As here two arguments are passed, while running java program args[0] and args[1] will be allowed, but args[2] will not. Same way if no arguments are passed, so java will not even allow args[0].
Java interprets the command line arguments as String array, as if we pass 2 arguments it is an array with args[0], args[1], if we pass 4 arguments it is an array with args[0], args[1], args[2], args[3] and when no arguments are passed it is still an String array object with no elements.
Thus, even when we do not pass any command line arguments to java program, still the args.length is equal to Zero - (0).
When you run a program, you can run the program passing command-line arguments. If the main method is:
public static void main(String args[])
the arguments will be received in the array of String called args. Now, regarding your question:
What does args.length mean?
It's the value of the built-in property length from arrays, which will be its fixed size. Note that arrays in Java are a special kind of objects.
args.length is the number of elements in the args[] array. The args[] array contains the parameters passed to the main function from the command line.
It is the number of elements in the args array, that was defined in public static main(String[] args).
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
}
}