In the last portion of this code (where the last for loop and if statements are), I'm trying to change the data type of the integers
to long
when they exceed the integer data type limit. What am I doing wrong in this code? When I run, I get the same values as before I even tried to change them to long (which are increasingly huge integers until they get negative).
public class UniqueElements {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
int maxValue = 0;
int numElements = 0;
int programRuns = 12;
Scanner sc = new Scanner(System.in);
for (int newExecution = 0; newExecution <= programRuns; newExecution++ ) {
System.out.print("Enter the maximum value for an element: ");
//prompt user to enter the maximum value
maxValue = sc.nextInt(); //user input for max value
System.out.print("Enter the number of elements in the array: ");
numElements = sc.nextInt(); //number of elements in an array
int A[] = new int[numElements];
//array comprising of the number of elements chosen by the user
int totalComp = 0; //set total comparisons to 0
for (int runs = 1; runs <= 100; runs++) { //program runs 100 times
Random rand = new Random(System.nanoTime());
//initiate the random number generator
int numComp = 0; //set number of comparisons to 0
for (int index = 0; index < numElements; index++) {
A[index] = rand.nextInt(maxValue);
//length of array is the number of elements the user puts in
}
for (int i = 0; i < A.length; i++) { //for each integer in the array
for (int j = i + 1; j < A.length; j++) {
//for each integer following i
if (A[i] == A[j]) { //if the are equal to eachother
//end the if statement
break;
}
if (numComp == (int)numComp) {
numComp++;
}
else {
Long.valueOf(numComp);
numComp++;
}
}
}
totalComp+= numComp;
} //end 100 loops
if (totalComp == (int)totalComp)
System.out.println("Average number of comparisons: " + totalComp / 100);
else {
System.out.println("Average number of comparisons: " +
Long.valueOf(totalComp) / 100L);
}
}
}
}