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?

5
  • Do you are passing args when you are running the code? Commented Feb 10, 2017 at 13:13
  • 1
    check args.lenght >0 Commented Feb 10, 2017 at 13:15
  • just pass an arg to your program. java TestCase Abc for example to enter in the first case Commented Feb 10, 2017 at 13:15
  • General hint: You should add a check if arguments have been actually passed. Never "trust" user input! A common practice is to output a "usage" - Message and exit. Commented Feb 10, 2017 at 13:16
  • If you running this from within an IDE like Eclipse you need to add arguments to your run configuration. Or if you are running it from a commandline then you do java TestCase yourstring. Commented Feb 10, 2017 at 13:19

2 Answers 2

1

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!

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks bro! helps a lot =D
You are very welcome. Feel free to accept at any time :-)
0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.