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

这在线程“main”java.lang.ArrayIndexOutOfBoundsException中不断出现异常:-1

因为它在数组字母表中找不到任何字符,请有人帮忙!

4

3 回答 3

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];
}
于 2012-07-12T01:18:28.003 回答
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());  
       }  
    }  
}  

这不一定是最好的方法,但我想帮助您理解这些概念。

于 2012-07-12T01:28:15.633 回答
0

问题的原因是方法的参数Arrays.asList是通用可变参数,(T... a)并且您使用的是原始字符数组。

解决方案:使用对象Character[] alphabet = {'a','b', ...}而不是原语char[] alphabet = {'a','b', ...},因为T...它不会威胁char[] alphabet作为对象数组,而是作为一个对象,因此您的列表将仅包含对该数组的引用。

于 2012-07-12T11:40:22.740 回答