Main () in java

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]);}

    }
}
+3
source share
5 answers

Arguments will never be null, if they exist in the first place - to verify that you should use instead args.length:

if (args.length == 0) {
  ...
} else {
  ...
}
+11
source

Not really - you want args.length==0:

if (args.length==0){
    System.out.println("Error- please type a string");
}
else {
    System.out.println(args[0]);
}

, , 0 , , IndexOutOfBoundsException.

+3

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]);
    }
}
+3
source

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.

+2
source

You want to check if there is args.length0.

+1
source

All Articles