Home java How to properly set Args arguments?

How to properly set Args arguments?

Author

Date

Category

I wanted to try to set one args argument [0] , depending on which the array will be output in direct or reverse order.
On the if (args [0] .compareto ("first") == 0) gives ArrayIndExOUTOFBOUNDSException: 0 .

What is the problem?

Public Class Main {
  Public Static Void Main (String [] Args) {
    int [] Massive = {1, 2, 3, 4, 5};
    if (args [0] .compareTo ("first") == 0) {
      For (int i = 0; I & lt; Massive.Length; I ++) {
        System.out.PrintLN (Massive [i]);
      }
    }
    ELSE If (Args [0] .compareTo ("Second") == 0) {
      For (int i = massive.length; I & gt; 0; i--) {
        System.out.PrintLN (Massive [i]);
      }
    }
    ELSE if (Args [0] == NULL || args.length == 0) {
      System.out.PrintLN ("Third");
    }
  }
}

Answer 1, Authority 100%

So, Added protection from ArrayIndexOUTOFBOUNDSException , Checks are modified (no dependence on the register of the argument), the first cycle is replaced by for-each , the second is changed so that everything would be displayed Elements of the array and did not fly the error.

Public Static Void Main (String [] Args) {
    int [] array = {1, 2, 3, 4, 5};
    if (args.length == 1 & amp; & amp; args [0] .equalsignorecase ("first")) {
      For (int anarray: array)
        System.out.printLN (Anarray);
    } ELSE if (args.length == 1 & amp; & amp; args [0] .equalsignorecase ("Second")) {
      for (int i = array.length-1; i & gt; = 0; i--)
        System.out.PrintLN (Array [i]);
    } ELSE if (args.length == 0)
      System.out.PrintLN ("Third");
  }

Run it stands through the console, the Java Main Firt / Second command
If you can set input parameters through IDE, such as in Intellij Idea, you can set about this: Run – & gt; Edit Configuration – & gt; Application In the Program Arguments field, you specify the argument (if there are several arguments, then specify it stands through the space).


Answer 2

Most likely you do not correctly convey the parameters when you start the program.
It needs to be done so

java & lt; class name with MAIN & GT; & lt; first parameter & gt; & lt; second parameter & gt;

More information about it can be read here

Programmers, Start Your Engines!

Why spend time searching for the correct question and then entering your answer when you can find it in a second? That's what CompuTicket is all about! Here you'll find thousands of questions and answers from hundreds of computer languages.

Recent questions