main() arguments in java
I'm trying to write a code for a program that recives strings as an input. The program prints "Error" when the user does not put any data, otherwise it prints the first string argument.
Is it right to refer to no data as a "null"? It does not work. what 开发者_JS百科should I write instead?
public class Try {
public static void main(String[] args){
if (args[0]==null){
System.out.println("Error- please type a string");
}else {System.out.println(args[0]);}
}
}
Arguments will never be null
if they exist in the first place -- to check that, you should use args.length
instead:
if (args.length == 0) {
...
} else {
...
}
Not quite - you want args.length==0
:
if (args.length==0){
System.out.println("Error- please type a string");
}
else {
System.out.println(args[0]);
}
With your current code it'll throw an exception if there isn't an argument, since the array will be of 0 length and accessing any element will thus throw an IndexOutOfBoundsException
.
you can check the value of args's attribute "length", if the value is 0, which means the user does not put any data
public class Try {
public static void main(String[] args){
if (args.length == 0) {
System.out.println("Error- please type a string");
} else {
System.out.println(args[0]);
}
}
Looks like this is being called from the command line. If the user doesn't provide any arguments then args
will be of length 0, so args[0]
will be an index out of bounds error. Instead of checking null you want to check the length of args
.
You'll want to test if args.length
is 0.
精彩评论