【问题标题】:Returning characters to an array from a method in JAVA [duplicate]从JAVA中的方法将字符返回到数组[重复]
【发布时间】:2018-10-15 19:27:13
【问题描述】:

我正在尝试将 4 个字符从一个方法返回到一个数组,但得到如下所示的错误。到目前为止,我已经尝试在两个位置调用该方法,并在下面将它们注释掉。这样做的正确方法是什么?

class App{

public static void main(String[]args){

    App theApp = new App();
}

    // position 1 - RandomizeCodeBlock(); 

    char[] charactersAllowed;
    char[] charArray;

    public App(){

        // position 2 - RandomizeCodeBlock(); 

         for(int i=0; i<4; i++){
         System.out.println(charArray[i]);
         }
    }

    public char RandomizeCodeBlock()
    {      
          char[] charactersAllowed = {'A','B','C','D','E','F','G'};
          charArray = new char[4];
          int i;

          for(i = 0; i < charArray.length; i++) {
          charArray[i] = charactersAllowed[(int) (Math.random() * 4)];
          }return charArray[i];
    }
}

我收到此错误:

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 4
    at App.RandomizeCodeBlock(App.java:33)
    at App.<init>(App.java:17)
    at App.main(App.java:5)

【问题讨论】:

  • currentCharacters 声明在哪里?
  • 抱歉,println 上的 currentCharacters 应该是 charArray。

标签: java arrays random methods


【解决方案1】:

我不完全确定您的代码应该这样做,但至少,问题在于 {return charArray[i]

你得到一个错误,因为此时 i 是 4,所以它超出了数组范围。

这样它至少会起作用,但我不确定它是否会给你预期的结果:

public class App{

public static void main(String[]args){

    App theApp = new App();
}

    public App(){


        char[] currentCharacters = randomizeCodeBlock();

         for(int i=0; i<4; i++){
         System.out.println(currentCharacters[i]);
         }
    }

    public char[] randomizeCodeBlock()
    {      
          char[] charactersAllowed = {'A','B','C','D','E','F','G'};
          charArray = new char[4];
          int i;

          for(i = 0; i < charArray.length; i++) {
          charArray[i] = charactersAllowed[(int) (Math.random() * 4)];
          }
          return charArray;
    }
}

我改变了什么:函数 randomizeCodeBlock() 返回一个随机数组。 然后按照您的建议将数组的内容打印到标准输出。

以防万一您可以使用 Java 集合,请看一下这篇文章,以确保 Collection.shuffle 方法对您不利。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-02-27
    • 2011-06-30
    • 2020-01-22
    • 1970-01-01
    • 2013-11-03
    • 2020-07-05
    • 2013-02-25
    • 1970-01-01
    相关资源
    最近更新 更多