Java - ArrayOutOfBoundsException帮助我 [英] Java - ArrayOutOfBoundsException help me
本文介绍了Java - ArrayOutOfBoundsException帮助我的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
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' ','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
因为它找不到数组字母表中的任何字符,有人可以帮助plz!
解决方案
indexOf(wordArray [i])
正在返回-1。我怀疑这是由于大写字母和/或特殊字符。首先执行此操作并添加错误检查:
word.toLowerCase()。toCharArray()
无论如何,我会做这样的事情,因为它更干净:
String alphabet =abcdefghijklmnopqrstuvwxyz;
,然后
code> int index = alphabet.indexOf(wordArray [i]);
if(index == -1){
//处理特殊字符
} else {
totalScore + = score [index];
}
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!
解决方案
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]; }
这篇关于Java - ArrayOutOfBoundsException帮助我的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文