0

Hello how do I change it so I don't get the error mentioned above? I don't know how to add or declare args[0] before.

public class DN02 {
    public static void main(String[] args) {
        if (args[0] == "1") {
            for (int x = 1; x < args.length - 1; x++) {
                if (x == args.length - 2) {
                    System.out.print(args[x]);
                } else {
                    System.out.print(args[x] + ", ");
                }

            }
        } else {
            System.out.println("**");
            System.out.println("* " + args + " *");
            System.out.println("**");
        }
    }
}
J.F.
  • 13,927
  • 9
  • 27
  • 65
  • You pass argument to your code so you can use them ? If you don't pass them, you have nothing to retrieve How do you call your code ? – azro Feb 27 '21 at 22:14
  • @azro Mind adding [this one](https://stackoverflow.com/questions/5554734/what-causes-a-java-lang-arrayindexoutofboundsexception-and-how-do-i-prevent-it)? (I expect OP wants the code to jump to the else block when it doesn't exist.) – Ivar Feb 27 '21 at 22:16
  • 2
    For the next problem you'll run into, see [How do I compare strings in Java?](https://stackoverflow.com/questions/513832/how-do-i-compare-strings-in-java) – Ivar Feb 27 '21 at 22:17

1 Answers1

0

You can check if args.length is at least 1:

if (args.length > 0 && args[0] == "1")
Amir MB
  • 3,233
  • 2
  • 10
  • 16