Unknown user
Unknown user

Reputation: 45331

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

    }
}

Upvotes: 4

Views: 30957

Answers (5)

opps
opps

Reputation: 270

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

Upvotes: 3

Jacob
Jacob

Reputation: 78920

You'll want to test if args.length is 0.

Upvotes: 1

Michael Berry
Michael Berry

Reputation: 72399

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.

Upvotes: 3

Herms
Herms

Reputation: 38868

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.

Upvotes: 2

casablanca
casablanca

Reputation: 70721

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 {
  ...
}

Upvotes: 11

Related Questions