2012-07-12 60 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为对象的数组,但作为一个对象,这样你的名单将只包含到数组引用。