2016-04-30 74 views
0

在下面的代碼中,如何更改持續顯示的消息(「C++」);根據數組的元素,根據 ?爲什麼會發生?爲什麼消息不會改變?NumberFormatException消息不會更改?

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 
+0

'語言[1]''是 「C++」',這不是一個'int'所以並不清楚你'num'期待什麼樣的價值。 –

+0

我知道,但爲什麼異常的消息(C++)不斷顯示,但元素更改! – user6162628

+0

一種是'語言[c]'另一種是'語言[1]',你是否看到了區別? –

回答

1

的信息是一樣的,因爲你總是獲得languages[1],這始終是字符串C++

爲了遍歷您的數組中的其它元素,你需要用你的食指c

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

不過,由於在評論中提到的,因爲你有一個String數組,它不是不太清楚你爲什麼使用Integer.parseInt來獲得int。它總是會導致NumberFormatException

相反,你應該有:

String language = languages[c]; 
+0

它是一個教程跟蹤問題(家庭作業),所以,我不能更改代碼,我可以嗎?> _ < – user6162628

+0

@ user6162628,哦好吧...雖然這個問題沒有提到。 :) – aribeiro