[英]What is causing the array out of bounds error and how can I clean up my code?
该程序应该在Scrable中将字母表中的每个字母的值都赋值,获取一个文本文件,处理各个单词,并打印出具有最高平均值的单词(平均值是所有字符,字母的总和)和非字母,除以这些字符的数量)。 我的代码似乎几乎完成了,但是它报告了超出范围的错误,我不知道为什么。
这是错误: java.lang.ArrayIndexOutOfBoundsException: -52
这是类驱动程序:
import java.util.Scanner;
import java.io.*;
public class ScrabbleDriver{
public static void main(String[] args) throws IOException{
try{
Scanner scan = new Scanner(System.in);
System.out.println("Enter text file ");
String fileName = scan.next();
Scrabble s = new Scrabble(fileName);
s.readLines();
s.report();
}
catch(Exception e){
System.out.println(e);}
}
}
这是构造函数类:
import java.io.IOException;
import java.util.StringTokenizer;
public class Scrabble extends Echo {
private int [] scores = {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};
private double maxScore = 0;
private String maxScoreWord = " ";
public Scrabble(String fn) throws IOException {
super(fn);
}
public void processLine(String line) {
line = line.toLowerCase();
StringTokenizer s = new StringTokenizer(line);
while (s.hasMoreTokens()) {
processToken(s.nextToken());
}
}
public void processToken(String token) {
double wordScore = 0;
for (int n = 0 ; n < token.length() ; n++) {
char j = token.charAt(n);
if ((j == '!') || (j == ',') || (j == '.'))
wordScore = wordScore;
else {
int m = (int) (j - 'a');
if (m <= 25) {
wordScore = wordScore + scores[m];
}
}
}
wordScore = (wordScore / token.length());
if (wordScore > maxScore) {
maxScore = wordScore;
maxScoreWord = token;
}
}
public void report() {
System.out.print("Winner: " + maxScoreWord + " " + "Score: " + maxScore);
}
}
这是回声类:
import java.util.Scanner;
import java.io.*;
public class Echo {
String fileName; // external file name
Scanner scan; // Scanner object for reading from external file
public Echo(String fn) throws IOException {
fileName = fn;
scan = new Scanner(new FileReader(fileName));
}
public void readLines() { // reads lines, hands each to processLine
while (scan.hasNext()) {
processLine(scan.nextLine());
}
scan.close();
}
public void processLine(String line) { // does the real processing work
System.out.println(line);
}
}
如果需要更多信息,请告诉我。
违规封锁
int m = (int)(j - 'a');
if(m <= 25){
}
您的错误是scores[m]
。 如果您选择的数组位置超出了scores
的长度(或小于scores
的长度),那么您将获得Out of Bounds Exception。 您需要首先检查数组的长度。 计算j - 'a'
产生一个负数。
最后,确保m
不小于零。 您正在检查它是否小于25。
这是ASCII表的链接。 表格中的char
少于“ a”。 因此,您需要调整逻辑。
由于您只使用大概的小写字母,因此在减去之前,需要确保字符值在97到122之间。 因此,您可以通过以下方式比较字母:
if (j < 'a' || j > 'z')
{
continue;
}
m
可能为负。 您只能在25岁以下进行测试。
在执行计算之前,请尝试确保j
(为什么命名为j
?)表示字母。
if (j < 'a' || j > 'z') {
continue;
}
或者,使用分词器确保奇怪的字符不属于“单词”。 取决于您要使用它的位置。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.