2012-07-12 61 views
-2
import java.util.*; 

import java.util.Arrays; 

public class ScoreCalc { 

    public static void main(String[] args) { 
     Scanner in = new Scanner(System.in); 
     char[] alphabet = {'a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z'}; 
     int[] score = {1,3,3,2,1,4,2,4,1,8,5,1,3,1,1,3,10,1,1,1,1,4,4,8,4,10}; 
     System.out.println("Enter word: "); 
     String word = in.nextLine(); 
     int totalScore = 0; 
     char[] wordArray = word.toCharArray(); 
     for(int i=0; i<wordArray.length; i++) { 
      System.out.println(wordArray[i]); 
      int index = Arrays.asList(alphabet).indexOf(wordArray[i]); 
      System.out.println(index); 
      totalScore = totalScore + score[index]; 
     } 
     System.out.println(totalScore); 
    } 
} 

這使得螺紋想出異常「主」 java.lang.ArrayIndexOutOfBoundsException:-1爪哇 - ArrayOutOfBoundsException幫我

,因爲它無法找到任何的字符數組中字母的人可以幫助PLZ!

+0

當你得到錯誤時,wordArray [i]的值是多少?另外請確保您使用的是全部小寫字母。 – twain249 2012-07-12 01:16:29

+0

@ twain249它提出了單詞中的第一個字母。所以如果我在「測驗」中寫道,它會打印「q」。並用-1打印索引。 – user1516514 2012-07-12 01:18:53

回答

1

indexOf(wordArray[i])正在返回-1。我懷疑這是由於大寫字母和/或特殊字符。爲此,首先,添加錯誤檢查:

word.toLowerCase().toCharArray() 

無論如何,我會做這樣的事情,而不是因爲它是乾淨多了:

String alphabet = "abcdefghijklmnopqrstuvwxyz"; 

然後

int index = alphabet.indexOf(wordArray[i]); 
if(index == -1) { 
    // handle the special character 
} else { 
    totalScore += score[index]; 
} 
+0

非常感謝你! @tskuzzy – user1516514 2012-07-12 01:23:11

+0

@Butaca:哈哈,是的,這是一種習慣。不知道這是好還是壞... – tskuzzy 2012-07-12 01:23:14

0

所以第一我的事將做到這一切都面向對象,如下所示:

public class CharacterScore //name this whatever makes you happy 
{ 
    int value; 
    char character; 

    public CharacterScore(int value, char character) 
    { 
    this.value=value; 
    this.character=character; 
    } //getters/setters 
} 

然後在你的主程序如下,你會做什麼:

private static List<CharacterScore> characterScores; 
static 
{ 
    characterScores = new ArrayList<CharacterScore>(); 
    String alphabet = "abcdefghijklmnopqrstuvwxyz"; 
    for(char current : alphabet.toCharArray()) 
    { 
    characterScores.add(new CharacterScore((int)Math.random() *10), current)); 
    } 
} 

現在,當你獲取用戶輸入您採取word其轉換爲char[]執行一些代碼,像這樣:

for(CharacterScore current : characterScores) 
{ 
    for(int i = 0; i <wordArray.length; i++) 
    { 
     if(current.getCharacter() == wordArray[i]) 
     { 
      recordScore(current.getValue()); 
     } 
    } 
} 

這不一定是實現這一目標的最佳方式,但我想幫助您理解這些概念。

0

問題的原因是方法Arrays.asList的參數是通用可變參數(T... a)並且您正在使用基元字符數組。

解決方法:使用對象Character[] alphabet = {'a','b', ...},而不是原語char[] alphabet = {'a','b', ...}因爲T...不threating char[] alphabet爲對象的數組,但作爲一個對象,這樣你的名單將只包含到數組引用。