I am trying to write code for a program that returns strings as input. The program prints "Error" when the user does not put any data, otherwise he prints the first string argument.
Is it right to refer to the lack of data as "zero"? This does not work. what 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 verify that you should use instead args.length:
null
args.length
if (args.length == 0) { ... } else { ... }
Not really - you want args.length==0:
args.length==0
if (args.length==0){ System.out.println("Error- please type a string"); } else { System.out.println(args[0]); }
, , 0 , , IndexOutOfBoundsException.
IndexOutOfBoundsException
you can check the value of the args attribute "length" if the value is 0, which means that 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]); } }
It looks like it is being invoked from the command line. If the user does not provide any arguments, then it argswill be 0, so it args[0]will be an index error outside the bounds. Instead of checking the null value, you want to check the length args.
args
args[0]
You want to check if there is args.length0.