Java - ArrayOutOfBoundsException help me

2019-09-22 09:53发布

问题:

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

This keeps coming up with Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: -1

Because it can't find any of the characters in the array alphabet can someone help plz!

回答1:

indexOf(wordArray[i]) is returning -1. I suspect this is due to uppercase letters and/or special characters. Do this first and add error checking:

word.toLowerCase().toCharArray()

Regardless, I would do something like this instead as it's much cleaner:

String alphabet = "abcdefghijklmnopqrstuvwxyz";

and then

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


回答2:

So the first thing I would do to make this all Object Oriented and such is the following:

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  
}  

Then in your main program you would do something as follows:

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

Now when you get user input you take the word convert it to a char[] execute some code like so:

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

This is not necessarily the best way to do this, but I wanted to help you understand the concepts.



回答3:

Cause of your problem is that argument of method Arrays.asList is generic vararg (T... a) and you are using array of primitive chars.

Solution: use object Character[] alphabet = {'a','b', ...} instead of primitives char[] alphabet = {'a','b', ...} because T... is not threating char[] alphabet as array of objects, but as one object so your list would contain only reference to that array.