I want to write a method that when supplied an array of ints will do the following. For each pair of array elements it will combine them and put them into a list of an inner class objects. Then it will compare each element in the array and check if it will fit between each pair values. (i.e. I have an array 0, 2, 4 it will make for example pair (0,4) and then it will check that value 2 is indeed between 0 and 4 so counter will increase). I tried the following code but it returned 0. How to fix it or is there an easier way to achieve that? I mainly care for the return value to be correct. thank you
import java.util.*;
import java.util.Map;
import java.lang.*;
public class Prac1 {
public int count(int[] A){
int k = 0;
class PTemp{
int first = -1;
int second = -1;
public PTemp(int first, int second){
int f = first;
int s = second;
}
}
List<PTemp> r = new ArrayList<PTemp>();
for (int i = 0; i < A.length; i++) {
for (int j = i+1; j < A.length; j++) {
r.add(new PTemp(A[i], A[j]));
r.add(new PTemp(A[j], A[i]));
//System.out.println("["+A[i] +","+A[j]+"]");
//System.out.println("["+A[j] +","+A[i]+"]");
}
}
Iterator<PTemp> ir = r.iterator();
while (ir.hasNext()){
PTemp p = ir.next();
for (int i = 0; i < A.length; i++){
if (((p.first < A[i]) && (A[i] < p.second)) || ((p.first > A[i]) && (A[i] > p.second))){
k = k + 1;
}
}
}
return k;
}
public static void main(String[] args){
int[] A = {0, 2, 4};
Prac1 pr = new Prac1();
System.out.println(pr.count(A));
}
}
Found a second bug in addition to the one mentioned by Alex D:
should really be:
Now the fields are properly set.