简体   繁体   中英

Method is not returning int

I have this method:

int totalNumGrades(){
    numTotal= numA+numB+numC+numD+numF;
    System.out.print("Total number of grades: ");
    return numTotal;
}

and all the variables are initialized like this:

private int numA, numB, numC, numD, numF, numTotal;

so lets say:

numA=3, numB=3, numC=2, numD=1, numF=1

therefore numTotal must equal 10. Here's the problem, when I run the code all I get in the output is:

Total number of grades:

and that's it, the numTotal doesn't show up. If I put numTotal inside the print statement, it comes out as 10 like it is supposed to, but for some reason when I try to return numTotal nothing shows up. I couldn't find a solution online so please help. What did I do wrong?

EDIT

Thanks for all the answers, that was quick, and excuse my lack of knowledge on this subject, I didn't know you could put methods inside a print statement. Learn something new everyday. Gracias amigos!

return numTotal; doesn't print anything. It just returns 10 to the place where the method was called from. Instead, change the code that called the method to

System.out.printf("Total number of grades: %d", totalNumGrades());

Then remove the print statement that is inside the method. It's best practice to not print things from inside methods unless that is the purpose of the method as described by the method name.

Also, don't store numTotal class-wide if you don't plan on using it class-wide.
Just do return numA+numB+numC+numD+numF;

You need to change

System.out.print("Total number of grades: ");

to

System.out.print("Total number of grades: " + numTotal);

Also, you can write similar print statement in caller method to print the return value.

To print something in Java you have to put it "inside a print statement" as you said.

There's no way to magically print values without passing them to print or println or equivalent.

Call method totalNumGrades() from main method
ex:

public static void main(String[] args){
    System.out.print(totalNumGrades());
}

OR

you can use in same method like

System.out.print("Total number of grades: " + numTotal);

I think you have not invoke the function you defined properly,this key word "return" just gives you the result,it will not print what it returns. flowing will work well:

System.out.print("Total number of grades: " + numTotal);

The string "Total number of grades:" has been show up,only because you invoked the function "System.out.print(...)".

hope this can help you.

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