Ozil
Ozil

Reputation: 954

What is wrong in this code? Why is it giving this error? How this can be removed?

I implemented this code using Java. It gave me an error saying "java.lang.ArrayIndexOutOfBoundsException" I'm not sure why? Also, I changed the integer I declared (int op=0;) to double with no change. The program works fine for +,/ and -. But not for *. Why is that so? Here's the code:

class test {
    public static void main(String [] mySpace) {
        double op=0;
        if (mySpace[0].equals("*")) {
             op=Integer.parseInt(mySpace[1])*Integer.parseInt(mySpace[2]);
        }
        System.out.println("Heya! "+ op);
    }
}

EDIT: I used these commands in the command prompt:

javac test.java // For compiling my source file with name test.java

java test * 10 20 //For execution

Upvotes: 1

Views: 135

Answers (4)

anshulkatta
anshulkatta

Reputation: 2064

EDIT

That's because * is a shell wildcard: it has a special meaning to the shell, which expands it before passing it on to the command (in this case, java).

Since you need a literal *, you need to escape it from the shell. The exact way of escaping varies depending on your shell, but you can try:

java test "*" 10 20

See this code

public class Test {

    public static void main(String args[]) {


        if(args[0].equals("*"))
        {
                   System.out.println("true");
                  }
                 else
                  System.out.println("false");

        }

}

now when i give the command

java Test.java * , it will print false

but when i give the command

java Test.java "*"  // it will print true

Upvotes: 1

Marko Topolnik
Marko Topolnik

Reputation: 200168

If you access mySpace[0], the array must have at least one element; else you'll get ArrayIndexOutOfBoundsException. Similarly for mySpace[1].

Therefore use mySpace.length to check the actual length of the array before trying to access any of its members. The legal indices range from 0 to mySpace.length-1; but you probably know that.

If your question is not about the exception itself, but about why Java didn't receive the command-line arguments you think you passed to it, then as a first step use

System.out.println(Arrays.toString(mySpace));

to diagnose what Java has actually received.

In particular, * has special meaning in many situations related to command-line parsing.

Upvotes: 5

PSR
PSR

Reputation: 40318

You need to pass command line arguments. Then you can acess them. You are accessing without passing any command line arguments.Then mySpace.length will be 0

But you are using mySpace[0] with out any element exist

Upvotes: 1

Reimeus
Reimeus

Reputation: 159784

You're not passing anything into your application hence the size of the array mySpace is 0. Try using

java test 123

Upvotes: 1

Related Questions