NumberFormatException消息没有改变?

时间:2016-04-30 19:18:53

标签: java

在下面的代码中,如何更改持续显示的消息(“C ++”); 根据数组的元素?为什么会这样?为什么消息不会改变?

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);
            }
        } 
    } 
}

输出:

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

1 个答案:

答案 0 :(得分:1)

消息是相同的,因为您总是获得languages[1],这始终是字符串C++

为了迭代数组的其他元素,您需要使用索引c

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

尽管如此,正如评论中所提到的,由于你有一个String数组,所以你不清楚为什么要使用Integer.parseInt来获得int。它总是会产生NumberFormatException

相反,你应该:

String language = languages[c];