Wagner Alves
Wagner Alves

Reputation: 11

Switch - Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 0

I´ve this issue in this test case program:

package testecase;

public class TesteCase {
    public static void main(String args []) {
        // TODO code application logic here
        switch (args [0] .charAt (0)) {
        case 'A':System.out.println("Vogal A ");
        break;

        case 'E':System.out.println("Vogal E ");
        break;

        default:System.out.println("Não é vogal ");

        }
    }
}

How can i solve it?

Upvotes: 0

Views: 250

Answers (2)

GhostCat
GhostCat

Reputation: 140467

The exception tells you that at runtime your args array doesn't have any entries.

You change that by invoking the JVM like

java TestCase A B C 

In other words: that array holds the parameters that you give to the JVM when starting it. No parameters on the command line ... ends up in an empty array.

Or giving another view: your code contains two assumptions about the incoming data:

  1. Using args [0] requires that the array has at least one entry
  2. Using ....charAt(0) requires that this first entry as at least one character

And guess what: that isn't necessarily true!

You learned your first, very valuable lesson about programming: do not expect that "reality" at runtime just matches your assumptions how it should look like.

Meaning: when data is coming in from the outside, the first step is to validate that it meets your expectations. Like:

if (args.length > 0) {
 ... process input
} else {
 tell user: no input

Similar for that String processing you intend to do!

Upvotes: 1

Migwel
Migwel

Reputation: 143

Make sure that you are sending an argument to your program when running it: java TesteCase A

Also, in general, you should not trust the user input so I'd advise you to check the lenght of args first. Once you know that it's not empty, you can try to read it.

Upvotes: 0

Related Questions