How to make an array created inside a loop work outside from it?

Gustavo Azevedo Correa :

I'm doing a java project to test different sorting algorithms and it is needed to use different typed of vector.

I determine the type of the vector whithin the code, so I need to declare it inside a loop. This is generating an error because of the array's scope. Is there anyway to make something similar or solving this error?

I'm on eclipse 2020, here is the code that is generating the error:

if(TypeOfVector(desorganized) == -1) {
    int[] organizedVector = PassingToIntVector(desorganized);}
if(TypeOfVector(desorganized) == 0) {
    float[] organizedVector = PassingToFloatVector(desorganized);}
if(TypeOfVector(desorganized) == 1) {
    double[] organizedVector = PassingToDoubleVector(desorganized);}
int organized = 0;
int duo;
int n = desorganized.size();
while(organized != n-1) {
    organized = 0;
    for (duo = 0; duo < n - 1; duo ++) {
        if(organizedVector[duo] > organizedVector[duo + 1]) {
            organizedVector[duo] = organizedVector[duo] - organizedoVector[duo +1];
            organizedVector[duo +1] = organizedVector[duo + 1] + organizedVector[duo];
            organizedVector[duo] = organizedVector[duo + 1] - organizedVector[duo];
        }
        else organized ++;
}

And here is an example of one of the PassingTo functions:

public float[] PassingToFloatVector(ArrayList<Object> list) {
        Object[] array = list.toArray();
        float[] desorganized = new float[list.size()];
        for(int i = 0; i < list.size(); i++) {
            desorganized[i] = (float) array[i];
        }
        return desorganized;
matt :

The first issue that you're asking about is scope. You need to declare your variable with scope to continue on.

if(TypeOfVector(desorganized) == -1) {
    int[] organizedVector = PassingToIntVector(desorganized);
}
if(TypeOfVector(desorganized) == 0) {
    float[] organizedVector = PassingToFloatVector(desorganized);
}

This would need to be changed because you're declaring your arrays within the if blocks and they will be lost once you leave the if block. ie They go out of scope.

int[] organizedVector;
if(TypeOfVector(desorganized) == -1) {
    organizedVector = PassingToIntVector(desorganized);
}
if(TypeOfVector(desorganized) == 0) {
    organizedVector = PassingToFloatVector(desorganized);
}

This will put organizedVector in a larger scope and you can use it after the if statements but you cannot assign it to a float[], so the second if statement will fail. Consider sticking with a List<Integer>, List<Float>, List<Double> which are all List<? extends Comparable>.

Then you can compare the elements, and swap them with collections.swap as necessary. Note that primitive arrays are not interchangeable. You'll have to write three different blocks of code to handle the three different array types.

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=374253&siteId=1