How to check the end of args array?

217 views Asked by At

I am writing a parser program in Scala that should read input using "args" and pars it. It doesn't matter I use:

   while(!args.isEmpty){ 
        if (Files.exists(Paths.get(args(j)))){
            Statement=Statement.concat(inputXml)
            Statement=Statement.concat(" ")
            println(j)
            }
         else{
            Statement=Statement.concat(args(j))
            Statement=Statement.concat(" ")
            println(j)
            }
    j=j+1
    }

or

   while(args.length !=0) { 
         if (Files.exists(Paths.get(args(j)))){
            Statement=Statement.concat(inputXml)
            Statement=Statement.concat(" ")
            println(j)
            }
         else{
            Statement=Statement.concat(args(j))
            Statement=Statement.concat(" ")
            println(j)
            }
    j=j+1
  }

The program gives me run time exception of array index out of bound! sending 2 values as input:

  Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 2

what should I do? I am confused!

3

There are 3 answers

1
Alex S. Diaz On BEST ANSWER

Your exception:

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 2

Is because you are not breaking the while loop; the args parameter never change it's size, so your while will go forever util j exceed the size of args.

Maybe you could try:

int i = 0
while (i < args.length){
    // some code here
    i++;
}

or

for(int i = 0; i < args.length; i++){
// some code here
}

If you want to iterate through all the array

0
elm On

Consider iterating over args without using indexed references (the source of out-of-bounds error),

for ( arg <- args ) yield {
  if (Files.exists(Paths.get(arg))) xmlFile
  else ""
}.mkString(" ")

This for comprehension yields a collection of String which is converted to a space-separated string with mkString.

0
fsb On

From what you describe, you need to iterate through your array while your index is lower than the maximum array size. If you merely compare args.length value, the loop condition will continue to evaluate to a truth value infinitely, since args.length will always be different than 0 (if not changed).

You need something along the lines of:

for(i <- 0 until array.length){
...

You can find extra information on accessing and iterating over arrays here and here