首页 > 解决方案 > 错误:线程“主”java.lang.ArrayIndexOutOfBoundsException 中的异常:索引 1 超出 Main.main 处长度 1 的范围(Main.java:16)

问题描述

我是初学者Java。我的代码是转换从键盘输入的摩尔斯电码并输出为有​​意义的字符。这只是一个 3 个字母的“A”“B”“C”测试,但是当我运行它时出现错误。请帮帮我 !

import java.util.*;
import java.io.*;

 public class Main {
 public static void main (String[] args) {
    String [][] Morse = new String[60][2];

        Morse[0][0] = "A" ; Morse[0][1] = ".-" ; 
        Morse[1][0] = "B" ; Morse[1][1] = "-...";
        Morse[2][0] = "C" ; Morse[2][1] = "-.-.";

    Scanner ip = new Scanner(System.in);
    String s = ip.nextLine();
    String [] op = s.split(" ");
    for (int i = 0 ; i <  60 ; i++) 
        if ( op[i] == Morse[i][1] ) System.out.print(" "+Morse[i][0]);
    }
}

标签: java

解决方案


欢迎来到堆栈溢出,请 在发帖前先阅读如何提问。

当您开始使用Java.

这是一个有用的链接,其中包含一些Data Structures处理面向对象的用例场景。

关于你的代码

首先看一下如何在Java中拆分字符串

  • 输入:“A”
 String [] op = s.split(" ");
//op[0] contains the A,B,C etc.
//op[1] is null because there is no space to split it with

  • 对于输入:“A(1 个空格)”
 String [] op = s.split(" ");
//op[0] contains the A,B,C etc.
//op[1] No "Space" to add to op[1]

  • 对于输入:“A(1+ 个空格)”
 String [] op = s.split(" ");
//op[0] contains the A,B,C etc.
//op[1] Still no "Space" to add to op[1]

解决方案:

更改if ( op[i] == Morse[i][1] )if ( op[0] == Morse[i][1] )

记住输入总是在数组的0索引处op

对我来说,它不会触发ArrayOutOfBoundsException你可以继续在你的案例中实现你的逻辑。


推荐阅读