简体   繁体   中英

Printing specific element from an array contained in a method

Trying to call one element from my array that is in a method. However, when I call and display the element, I get a compiling error. I don't know how to properly print out an individual level.

sortMarks is an arrayList, and has already been initialized.

The code is supposed to display how many marks that the user inputted in a specific level. This is all done in a GUI.

Here's my code:

private int[] arrayToLevel() {
    //Creating array for the different levels
    int levels[] = {0, 0, 0, 0, 0};

    //Finding how many marks at a certain level using the levels array
    int grade;
    for(int i=0; i<sortMarks.size(); i++) {

    grade = sortMarks.get(i);

    if (grade < 50) {
        levels[0] = levels[0]+1;           
    }
    else if(grade >= 50 && grade < 60){
        levels[1] = levels[1]+1;            
    } 
    else if (grade >= 60 && grade < 70){
        levels[2] = levels[2]+1;            
    } 
    else if (grade >= 70 && grade < 80){
        levels[3] = levels[3]+1;            
    } 
    else if (grade >= 80){
        levels[4] = levels[4]+1;            
    }        

    }

    return levels;
}

Here is where my errors begins, I don't know how to properly print this out.

analyseMarks.append("\nStudents at Level R: " + arrayToLevel.get[0].toString());

analyseMarks.append("\nStudents at Level 1: " + arrayToLevel.get[1].toString());

    //and so on for the rest of the levels.

EDIT:

Just to let every know for future reference my compilation error was

cannot find symbol
symbol: variable arrayToLevel

It is not completely clear without the compilation error, but I believe the problem is with the attempted use of .get on an int[] .

Changing to be:

analyzeMarks.append(... + Integer.toString(arrayToLevel()[0]));

should resolve the compilation error.

The correct way to use the result of your method is :

arrayToLevel()[0]

Instead of this :

arrayToLevel.get[0].toString()

You don't even need to use toString() , because it will be concatinated with a String

Also Instead of :

analyseMarks.append("\nStudents at Level R: " + arrayToLevel());

the practice way to append to StringBuilder is :

analyseMarks.append("\nStudents at Level R: ");
analyseMarks.append(arrayToLevel()[0]);

Or :

analyseMarks.append("\nStudents at Level R: ").append(arrayToLevel()[0]);

You only need to call the method once. Use a reference to the return value in your print statements.

int[] levels = arrayToLevel();

analyseMarks.append("\nStudents at Level R: " + levels[0]); 
analyseMarks.append("\nStudents at Level 1: " + levels[1]);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM