Home > database >  Absolutely dead confused about what is going in this code and problem. Can someone explain to me whe
Absolutely dead confused about what is going in this code and problem. Can someone explain to me whe

Time:01-20

I have to apply linear scan to this problem, and I just don't even know where to start. I feel as if I should change my career path honestly, this is a simple intro problem and i'm just not understanding anything about it.

/**
 * Applies the linear scan strategy to counting the number of negative
 * values in an array.
 */
public class CountNegatives {

    /**
     * Returns the number of negative values in the given array.
     */
    public static int countNegatives(int[]a) {
        neg=0;
        for{i=0;i<a.length;i  }
            if(i>0)
                neg = neg 1;
        return neg;
        
    }
}

I've tried running this in VS and a tool my school uses called JGrasp. Both told me the { should be ( , the ; between length and i should be > , i<a.length is not a statement, and that } should be ;

When I change any of these things, it tells me variable neg=0 cannot be found and doubles the amount of errors in the code.

CodePudding user response:

public class CountNegatives {
/**
 * Returns the number of negative values in the given array.
 */
public static int countNegatives(int[]a) {
        int neg=0;
        for(int number : a){
            if(number<0) {
                neg=neg 1;
            }
        }
        return neg;
    }
}

CodePudding user response:

There are a few things you missed,

  1. You did not initialize the neg=0; value with the proper data type; you should initialize it with the proper data type, which int his case is int, correct initialization would be int neg = 0;

  2. the other problem would be in the for loop you still need to initialize i with a data type

  3. the if statement is wrong, it should be 'i<0' instead cause with your code you are just counting the positive values

  4. You are comparing the index value with 0 so you won't get the right value, instead, you should compare the value in the array that on that index, array[index].

The correct code would be as follows:

static int countNegatives(int[] a) {
        
        int neg = 0;
        
        for(int i = 0; i < a.length; i  ) {
            if(a[i] < 0) neg  ;
            // this will just work as neg = neg  1;
        }
        
        return neg;
    }
}
  • Related