Hello Everyone,
I have encountered this type of code
public static void main ( String [] args)
// And immediately
int n = Integer.parseInt(args[0]);
// In here what does args[0] mean? // are we just supposed to use args[] in static void main
Args is the name of the string array brought in by the "main" function. It holds whatever you wrote on the command line when running the program. Something like:
/myprogram 1
would have "1" as args[0]
Integer.pareInt assumes args[0] is a number and casts it appropriately.
You can pass String arguments via the command line to the main method when you execute the program. It’s just saying then parse the first String in the array
Videos
You could assign value of n as 0 or any other value by default and use if(args.length > 0) { to check whether any arguments is given. Below is full example with comments:
public class Infinity {
public static void main(String args[]) {
/*
Start by assigning your default value to n, here it is 0
If valid argument is not given, your program runs
starting from this value
*/
int n = 0;
// If any arguments given, we try to parse it
if(args.length > 0) {
try {
n = Integer.parseInt(args[0]);
} catch (NumberFormatException e) {
System.err.println("Argument" + args[0] + " must be an integer.");
// Program ends
System.exit(1);
}
}
// All good, n is either default (0) or user entered value
while(true) {
System.out.println(n);
n++;
}
}
}
Note: Users which are not so familiar with java, this program can be run by:
- Saving it to
Infinity.java - Compiling it with cmd or terminal by writing:
javac Infinity.java - Executing it with:
java Infinityorjava Infinity 1000(or any other value)
Cheers.
Check the length of the args array before attempting to access.
int n = 0;
if (args.length == 1)
{
n = Integer.parseInt(args[0]);
}
You still likely need a try/catch block if you want to handle an argument being provided that is not a valid integer.