Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
295 views
in Technique[技术] by (71.8m points)

arrays - Java - ArrayOutOfBoundsException help me

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!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...