简体   繁体   English

是什么导致数组越界错误,如何清除代码?

[英]What is causing the array out of bounds error and how can I clean up my code?

This program is supposed to ascribe each letter of the alphabet its value in Scrable, take a text file, process the individual words, and print the word with the highest value average value (with the average value being the total value of all characters, letters and non-letters, divided by the number of those characters). 该程序应该在Scrable中将字母表中的每个字母的值都赋值,获取一个文本文件,处理各个单词,并打印出具有最高平均值的单词(平均值是所有字符,字母的总和)和非字母,除以这些字符的数量)。 My code seems almost complete but it reports an out of bounds error and I dont know why. 我的代码似乎几乎完成了,但是它报告了超出范围的错误,我不知道为什么。

This is the error: java.lang.ArrayIndexOutOfBoundsException: -52 这是错误: java.lang.ArrayIndexOutOfBoundsException: -52

This is the class driver: 这是类驱动程序:

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

This is the constructor class: 这是构造函数类:

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

This is Echo class: 这是回声类:

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

If any more info is needed, let me know. 如果需要更多信息,请告诉我。

Offending block 违规封锁

int m = (int)(j - 'a');
if(m <= 25){

wordScore = wordScore + scores[m]; wordScore = wordScore +分数[m];

}

Your error is in scores[m] . 您的错误是scores[m] If you select an array position beyond the length (or less than) of scores , then you will get an Out of Bounds Exception. 如果您选择的数组位置超出了scores的长度(或小于scores的长度),那么您将获得Out of Bounds Exception。 You need to check the length of your array first. 您需要首先检查数组的长度。 The calculation j - 'a' is producing a negative number. 计算j - 'a'产生一个负数。

Finally, ensure that m is not less than zero. 最后,确保m不小于零。 You are checking if it is less than 25. 您正在检查它是否小于25。

Here is a link to an ASCII table . 这是ASCII表的链接。 There are char less than 'a' in the table. 表格中的char少于“ a”。 Therefore, you need to adjust your logic. 因此,您需要调整逻辑。

Since you are only working with presumably lower case letters, you need to make sure that your character value is between 97 and 122 before subtracting. 由于您只使用大概的小写字母,因此在减去之前,需要确保字符值在97到122之间。 So, you can compare the letters by saying: 因此,您可以通过以下方式比较字母:

if (j < 'a' || j > 'z')
{
   continue;
}

Probably m is negative. m可能为负。 You only test against 25 or less. 您只能在25岁以下进行测试。

Try to make sure that j (why name it j ?) represents a letter before doing the calculation. 在执行计算之前,请尝试确保j (为什么命名为j ?)表示字母。

if (j < 'a' || j > 'z') {
    continue;
}

Or, alternatively, make sure that strange characters are not part of a "word" using the tokenizer. 或者,使用分词器确保奇怪的字符不属于“单词”。 Depends on where you want to go with it. 取决于您要使用它的位置。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 我的代码有什么问题,它说数组越界索引-1 - what is wrong with my code it says array out of bounds index -1 我不断收到“字符串超出范围”错误,有人可以帮助修复我的代码吗? - I keep getting a String out of bounds error, can someone help fix my code? 我正在尝试在Java的多维数组中对角地向上搜索。 为什么我出现索引超出范围错误? - I am trying to search up to the right diagonally in my multidimensional array in java. Why am I getting index out of bounds error? 如何清理我的代码 - How to clean up my code 如何重写我的代码,以使 0 的值不会在 java 中给我一个越界错误? - How do I rewrite my code so that the value of 0 does not give me a out of bounds error in java? 如何在Java代码中修复“坐标超出范围”错误? - How do I fix the “Coordinates out of bounds” error in my code in Java? 是什么导致我的代码冻结? 我没主意 - What is causing my code to freeze? I am out of ideas 错误数组索引超出某些代码的范围 - Error array index out of bounds in some code 在具有两个对象的数组中,如何在(1)处获得超出范围的异常? - In an array with two objects, how can I be getting an out of bounds exception at (1)? 如何清理Java流? - How can I clean up my Java Streams?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM