array comparison

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • loverahul3
    New Member
    • Mar 2008
    • 1

    #1

    array comparison

    hi,

    i want to return true if previous value in an arry is >= current vallues and false if <=..
    int d= scores[i+1]; this line is throwing the arrayindexoutof bonds error pls help.

    Given an array of scores, return true if each score is equal or greater than the one before. The array will be length 2 or more.

    scoresIncreasin g({1, 3, 4}) → true
    scoresIncreasin g({1, 3, 2}) → false
    scoresIncreasin g({1, 1, 4}) → true


    public boolean scoresIncreasin g(int[] scores) {
    int a= scores.length;
    boolean b = false;
    for (int i=0; i<=a;i++){
    int c =scores[i];
    int d= scores[i+1];
    if (a>=2 && c<=d) b= true;
    }
    return b;
    }
  • rodeoval
    New Member
    • May 2007
    • 15

    #2
    The code gives the arrayIndexOutOf Bounds error because inside the for loop you have used the following condition inside for loop.
    for (int i=0; i<=a;i++).
    Since array indexes are 0 based the last index of the array is always (length-1).(eg: if it is an array of length 2, then the last index is 1).Therefore normally the condition should be i<a .Also since you are comparing two consective values here, the condition should be i<(a--1), so that in the last step of the iteration scores[a-2]and scores[a-1] will be compared.

    Also note that rather than checking whether the length of the array in each iteration you can check it prior to the loop.If the length>= 2 then you can go to the for loop.Otherwise do something else.This way there would be lesser amnt of processing to do.

    Comment

    • r035198x
      MVP
      • Sep 2006
      • 13225

      #3
      Originally posted by loverahul3
      hi,

      i want to return true if previous value in an arry is >= current vallues and false if <=..
      int d= scores[i+1]; this line is throwing the arrayindexoutof bonds error pls help.

      Given an array of scores, return true if each score is equal or greater than the one before. The array will be length 2 or more.

      scoresIncreasin g({1, 3, 4}) → true
      scoresIncreasin g({1, 3, 2}) → false
      scoresIncreasin g({1, 1, 4}) → true


      public boolean scoresIncreasin g(int[] scores) {
      int a= scores.length;
      boolean b = false;
      for (int i=0; i<=a;i++){
      int c =scores[i];
      int d= scores[i+1];
      if (a>=2 && c<=d) b= true;
      }
      return b;
      }
      Print out the values of i at every entry in the for loop so that you understand how the indexing works.

      P.S This is a contradiction
      "i want to return true if previous value in an arry is >= current vallues and false if <=.."

      Comment

      Working...