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
因为它找不到数组字母表中的任何字符,所以有人可以帮助PLZ!
答案 0 :(得分: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];
}
答案 1 :(得分: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());
}
}
}
这不一定是最好的方法,但我想帮助您理解这些概念。
答案 2 :(得分:0)
问题的原因是方法Arrays.asList
的参数是通用的vararg (T... a)
,并且您使用的是原始字符数组。
解决方案:使用对象Character[] alphabet = {'a','b', ...}
而不是基元char[] alphabet = {'a','b', ...}
,因为T...
不会将char[] alphabet
作为对象数组,而是作为一个对象,因此您的列表仅包含引用那个数组。