gpt4 book ai didi

java - Java-ArrayOutOfBoundsException帮助我

转载 作者:行者123 更新时间:2023-12-02 11:12:51 24 4
gpt4 key购买 nike

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!

最佳答案

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

关于java - Java-ArrayOutOfBoundsException帮助我,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11443800/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com