user6162628
user6162628

Reputation: 7

NumberFormatException message doesnt change?

In the following code, how can I change the message that keeps displaying ("C++"); according to the element of the array? and why does that happened? why the message doesn't change?

import java.util.*;

public class Testslsl {

    static Scanner input = new Scanner(System.in);

    public static void main(String[] args) {

        String languages[] = {"C", "C++", "Java", "Perl","Python" };

        int num;

        for (int c = 0; c <= 5; c++) {
            try {
                System.out.println(languages[c]);

                if (languages[c].charAt(2)=='+')
                    System.out.println("it is C plus plus");

                num = Integer.parseInt(languages[1]);
            }
            catch (NumberFormatException e) {
                System.out.println(e);
                input.next();
            }
            catch (ArrayIndexOutOfBoundsException ex) {
                System.out.println(ex);
            }
            catch (StringIndexOutOfBoundsException exp) {
                System.out.println(exp);
            }
        } 
    } 
}

Output:

C
java.lang.StringIndexOutOfBoundsException: String index out of range: 2
C++
it is C plus plus
java.lang.NumberFormatException: For input string: "C++"
Java
java.lang.NumberFormatException: For input string: "C++"
Perl
java.lang.NumberFormatException: For input string: "C++"
Python
java.lang.NumberFormatException: For input string: "C++"
java.lang.ArrayIndexOutOfBoundsException: 5

Upvotes: 0

Views: 472

Answers (1)

Ant&#243;nio Ribeiro
Ant&#243;nio Ribeiro

Reputation: 4202

The message is the same because you're always attaining languages[1], which is always the string C++.

In order to iterate over the other elements of your array, you'll need to use your index c:

num = Integer.parseInt(languages[c]);

Nevertheless, as mentioned in the comments, since you have a String array, it isn't quite clear why you're using the Integer.parseInt in order to attain an int. It will always result in a NumberFormatException.

Instead, you should have:

String language = languages[c];

Upvotes: 1

Related Questions