2015-10-04 3 views
1

Я пытаюсь создать программу на Java, которая преобразует код Морзе на английский. В этом случае буквы отделены друг от друга одним пробелом и слова разделены на три пространства:.Код Морзе на Английский: ArrayIndexOutOfBoundsException

import java.util.Scanner; 

public class ReverseMorseCodeProgram { 
    public static void main(String[] args) { //Converts Morse Code into English 

    System.out.println("Enter the Morse Code to be converted to English (letters and spaces only, no numbers or punctuation):"); 
    String sentence = new Scanner(System.in).nextLine(); //Input is converted into String 
    char[] dotdash = sentence.toCharArray(); //String is converted into char[] 
    String[] words = new String[30]; //String array where char[] is converted into morse code letters 
    int y = 0; 
    int x = 0; 

    while (dotdash[x] < dotdash.length) { //Converts char[] into String[] 

    while (dotdash[x] != ' ') { //loops until a space is encountered 
     words[y] = words[y] + dotdash[x]; //adds chars to String in array 
     x = x + 1; //goes to next char in array 
    } 

    if ((dotdash[x+1] == ' ') && (dotdash[x+2] == ' ')) { //determines whether there are three spaces in a row 
     words[y+1] = " "; //adds " " as next string in array 
     y = y + 2; //moves to string after " " 
     x = x + 3; //moves to char after the three spaces 
    } 
    else { //if there's only one space 
     y = y + 1; //moves to next string in String[] 
     x = x + 1; //moves to next char in char[] 
    } 
    } 

    char[] alphabet = {'a', 'b', 'c', 'd', //English alphabet array 
    'e', 'f', 'g', 'h', 
    'i', 'j', 'k', 'l', 
    'm', 'n', 'o', 'p', 
    'q', 'r', 's', 't', 
    'u', 'v', 'w', 'x', 
    'y', 'z', ' '}; 
    String[] morse = {".-", "-...", "-.-.", "-..", //morse code alphabet array 
    ".", "..-.", "--.", "....", 
    "..", ".---", "-.-", ".-..", 
    "--", "-.", "---", ".--.", 
    "--.-", ".-.", "...", "-", 
    "..-", "...-", ".--", "-..-", 
    "-.--", "--..", " "}; 


    for (int i = 0; i < words.length; i++) { //repeats until end of String array 
    for (int t = 0; t < 27; t++) { //goes through morse code array 
     if (morse[t] == words[i]) { //compares morse code to each word in String array 
     System.out.print(alphabet[t]); //prints equivalent english letter when match is found 
     } 
    } 
    } 
    } 
} 

Однако, когда я ввести фразу «- -.-- ..- .- ...- - - ..- .-. .. -. -.-. --- .- .. --- .-. .. ... .-. - .. ", появляется следующая ошибка:

java.lang.ArrayIndexOutOfBoundsException: 78 
    at ReverseMorseCodeProgram.main(ReverseMorseCodeProgram.java:15) 
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) 
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39) 
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25) 
    at java.lang.reflect.Method.invoke(Method.java:597) 
    at edu.rice.cs.drjava.model.compiler.JavacCompiler.runCommand(JavacCompiler.java:272) 

Ввод более короткой строки, такой как «-», не приводит к выходу вообще.

Я довольно новичок в программировании, и это меня озадачило.

редактировать: Я изменил раздел обижая от:

while (dotdash[x] < dotdash.length) { //Converts char[] into String[] 

    while (dotdash[x] != ' ') { //loops until a space is encountered 
     words[y] = words[y] + dotdash[x]; //adds chars to String in array 
     x = x + 1; //goes to next char in array 
    } 

    if ((dotdash[x+1] == ' ') && (dotdash[x+2] == ' ')) { //determines whether there are three spaces in a row 
     words[y+1] = " "; //adds " " as next string in array 
     y = y + 2; //moves to string after " " 
     x = x + 3; //moves to char after the three spaces 
    } 
    else { //if there's only one space 
     y = y + 1; //moves to next string in String[] 
     x = x + 1; //moves to next char in char[] 
    } 
    } 

Чтобы следующее:

while (x < dotdash.length) { //Converts char[] into String[] 

    while (dotdash[x] != ' ') { //loops until a space is encountered 
     words[y] = words[y] + dotdash[x]; //adds chars to String in array 
     x = x + 1; //goes to next char in array 
    } 

    if (((x+2) < dotdash.length) && ((y+1) < words.length)) { //ensures that dotdash[x+2] and (y+1) doesn't exceed their respective boundaries 

     if ((dotdash[x+1] == ' ') && (dotdash[x+2] == ' ')) { //determines whether there are three spaces in a row 
     words[y+1] = " "; //adds " " as next string in array 
     y = y + 2; //moves to next string after " " 
     x = x + 3; //moves to next char after the three spaces 
     } 
     else { //if there's only one space 
     y = y + 1; //moves to next string in String[] 
     x = x + 1; //moves to next char in char[] 
     } 

    } 

    } 

Однако ошибка ArrayIndexOutOfBoundsException сохраняется. Кажется, я не вижу места, где я мог бы превышать границы массива.

ответ

0

В строке 15, измените время (dotdash [x] < dotdash.length) до (x < dotdash.length). dotdash [x] - элемент dotdash с индексом x. Вы не хотите сравнивать это с длиной массива, вы хотите сравнить индекс (x) с длиной массива.

Могут быть другие проблемы, я не смотрел за пределы этого, потому что это то, что вызывает исключение.

On edit: После того, как вы посмотрите немного дальше, у вас есть несколько мест, где может возникнуть ArrayIndexOutOfBoundsException. В любом месте вы берете элемент массива, поэтому dotdash [x + 1] и т. Д., Если элемент, который вы пытаетесь получить, находится за пределами массива, вы получите исключение ArrayIndexOutOfBoundsException, поэтому вам нужно сделать уверен, что х + 1 < dotdash.length, прежде чем пытаться получить dotdash [х + 1] и т.д.

+0

Я внес несколько изменений (добавлен в редактирование моего сообщения), но ошибка, похоже, сохраняется ... –

+0

ArrayIndexOutOfBoundsException сообщает вам, в какой строке происходит исключение, поэтому просмотрите код этой строки, чтобы увидеть, как вы можете ссылаться за пределы массива. Я предполагаю, что это будет где-то в первом внутреннем цикле, где вы никогда не проверяете длину. – blm

0
while (dotdash[x] < dotdash.length) 

Это не имеет никакого смысла (для меня на первый взгляд). Значение в массиве не является числом.

Я думаю, что вы имели в виду:

while (x < dotdash.length) 

Таким образом, вы можете индексировать все записи в массиве.

Конечно, как только вы делаете, что теперь вы будете иметь проблемы с:

if ((dotdash[x+1] == ' ') && (dotdash[x+2] == ' ')) 

потому, что «х + 1» и «х + 2» может быть больше, чем длина массива.

Так что, если заявление может быть выполнено только тогда, когда х < dotdash.length - 2.

Таким образом, вы должны перестроить ваш код немного.

Смежные вопросы