(Java) 检查数组是否有增加的元素

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7143118/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 18:50:21  来源:igfitidea点击:

(Java) Check array for increasing elements

javaarrays

提问by jlss4e

I'm attempting to create a method that checks an array for increasing elements. True should be returned if all the elements are in increasing order. I get an out-of-bounds exception when I compare arr[i+1]. Any ideas on how I can make it work.

我正在尝试创建一个方法来检查数组中的元素是否增加。如果所有元素都按升序排列,则应返回 True。当我比较 arr[i+1] 时,出现越界异常。关于如何使其工作的任何想法。

int[] one = {1,2,3,4,5};

public static boolean isIncreasing(int[]arr)
{
    boolean z = false;

    for(int i=0; i<arr.length;i++)
    {

        if(arr[i]<arr[i+1])
            {
                z = true;
            }
    }

    return z;
}

回答by Owen

Because in a list with nitems there are only n-1gaps between them.

因为在包含n项目的列表中,n-1它们之间只有间隙。

Change to

改成

for (int i=0; i<arr.length-1; i++)

(Also you might want to check whether starting with falseand setting to trueis the right way around).

(此外,您可能还想检查开始false和设置是否true是正确的方法)。

回答by Bohemian

You have two problems:

你有两个问题:

  1. Your loop is one iteration too long: Because you are checking element i+1, i needs to finished incrementing one iteration earlier than a usual loop.
  2. Your logic is flawed. Your loop will terminate the first timethe check is true, so this array will pass: {1, 2, 0}when tested the first iteration tests 1 < 2which is true, so return true - this is not what we want)
  1. 您的循环一次迭代太长:因为您正在检查 element i+1,所以我需要比通常的循环更早完成一次迭代。
  2. 你的逻辑有问题。您的循环将在第一次检查为真终止,因此该数组将通过:{1, 2, 0}测试时第一次迭代测试1 < 2为真,因此返回真 - 这不是我们想要的)

Fixing these two problems:

解决这两个问题:

int[] one = {1,2,3,4,5};

public static boolean isIncreasing(int[] arr) {
    for(int i=0 ; i < arr.length - 1; i++) { // finish at length - 1
        if (arr[i] > arr[i+1]) {
            return false; // found elements that are out of order - return false
        }
    }    
    return true; // nothing out of order found - return true
}

This kind of logic - with an early exit with false on problem and a final return of true - is very common and a good pattern to learn.

这种逻辑——在问题上以 false 提前退出,最终返回 true——非常普遍,是一种很好的学习模式。

回答by Nicolas Modrzyk

I suggest you write your method like this

我建议你这样写你的方法

public static boolean isIncreasing(int[]arr)
{
    for(int i=1; i<arr.length;i++)
    {
        if(arr[i-1]>arr[i])
            return false;
    }
    return true;
 }

it will help

我会帮你的

  • return the proper result (yours returns true when it should not)
  • consider out of bounds
  • avoid unnecessary looping
  • 返回正确的结果(你的结果不应该返回真)
  • 考虑越界
  • 避免不必要的循环

回答by wannik

You can use Java 8's IntStream.

您可以使用 Java 8 的 IntStream。

import java.util.stream.IntStream;

public class Test {
  public static boolean isIncreasing(int[] a) {
    return IntStream.range(1, a.length).reduce(0, (acc, e) -> acc + (a[e - 1] <= a[e] ? 0 : 1)) == 0;
  }
}

回答by Swagatika

You get that exception as when (i+1)'s value becomes array.length. For example if you have an array of length 10, the elements indexes will be from 0,1,2...till 9. so either you have to check till i < arr.length - 1or you can modify your logic accordingly.

当 (i+1) 的值变为 array.length 时,您会得到该异常。例如,如果您有一个长度为 10 的数组,则元素索引将从 0,1,2...直到 9。因此您必须检查直到i < arr.length - 1或者您可以相应地修改您的逻辑。