【问题标题】:Writting a boolean method with float array and a boolean as parameters使用浮点数组和布尔值作为参数编写布尔方法
【发布时间】:2023-11-22 21:18:01
【问题描述】:

我必须编写一个程序来检查数组中的数字是否按升序排列。我写了代码,但我得到了这个错误。我必须以某种方式实现这两个参数

boolean isSorted(float[] numbers, boolean ascending){
    //tell if the numbers are ascending (ascending == true), or not (ascending == false)
    boolean s=ascending;
    for(int i = 0; i < numbers.length; i++){
            s= numbers[i] < numbers[1+i];
    }
    return s;
}

boolean a=isSorted(new float[]{1,7,8,9,10,14},true);
System.out.println(a);

这是我返回的错误

created method isSorted(float[],boolean)
|  Exception java.lang.ArrayIndexOutOfBoundsException: Index 5 out of bounds for length 5
|        at isSorted (#7:5)
|        at (#9:1)
true

【问题讨论】:

  • it compiles 你确定吗?根据您的编辑,它没有
  • 你在调用它时永远不会传入一个布尔值。你需要做boolean a=isSorted(new float[]{1,7,8,9,10,14}, true);(或假)
  • 您发布的错误消息告诉您发生了什么。它找到了float[],但预期的是float[], boolean
  • 一旦你的i到达numbers.length - 11 + i就会触发AIOOBE。

标签: java arrays sorting oop boolean


【解决方案1】:

您得到运行时异常(ArrayIndexOutOfBoundsException),因为在 for 循环的最后一次迭代中,解释器试图访问一个不存在的元素(数字 [1+i]),因此在此逻辑之前保留一个 if 条件会做如下的伎俩

boolean  isSorted(float[] numbers, boolean ascending){
    //tell if the numbers are ascending (ascending == true), or not (ascending == false)
    boolean s=ascending;
    for(int i = 0; i < numbers.length; i++){
        //added this if condition to avoid ArrayIndexOutOfBoundsException
        if(i == numbers.length-1){
            continue;
        }
        s= numbers[i] < numbers[1+i];
    }
    return s;
}

【讨论】:

  • 即使我基本上复制粘贴了这段代码,我仍然得到同样的错误
  • 您是否更新了答案中提供的 isSorted() 函数或仅更新了第一行?
  • 对不起,我刚刚意识到错误,让我为你更新答案
最近更新 更多