Call method with parameter with vector elements defined
Good night!
I have created a method that calculates the elements of a vector and averages it overall, but I am not able to call it in the main method. PS: I'm a beginner.
I appreciate the help right now!
package proj04;
public class media {
private static double mediatotal;
private static double[] notasAlunos = {10, 5, 7, 8, 6, 8, 10, 9, 7, 6, 7, 6, 8, 4, 6};
public static double getMediatotal() {
return mediatotal;
}
public static void setMediatotal(double mediatotal) {
media.mediatotal = mediatotal;
}
public static double mediat(double notasAlunos[]) {
double soma = 0;
for (int i = 0; i < 15; i++) {
soma = (soma + notasAlunos[i]) / 15;
mediatotal = soma;
}
return soma;
}
}
package proj04;
public class exe4main {
public static void main(String[] args) {
double mediavar;
media mediaturma = new media();
System.out.println( mediaturma.getMediatotal());
}
}
1 answers
I did not find the error in your code, but I leave some tips.
Usually class name starts with capital letter.
The functions and variables of your class media
are all static
so you don't need to create an instance of it new media()
you can access directly by the ex Class. media.getMediatotal()
.
In main
you are giving print on the return of getMediatotal
which at this time is still null.
You set private static double[] notasAlunos
to private so you won't be able to access it out of class media
and apparently you want to pass it to function mediat
, options:
Change the
private
topublic
or leave without either of them, without either of them will work because they are in the samepackage
.Do not receive
notasAlunos
per parameter in functionmediat
access from within it.
I made some changes to your code and put it formatted to run on Ideone see it in execution
class Exe4main
{
public static void main (String[] args) // throws java.lang.Exception
{
double mediavar;
Media.mediat( Media.notasAlunos );
System.out.println( Media.getMediatotal() );
}
}
class Media {
private static double mediatotal;
public static double[] notasAlunos = {10, 5, 7, 8, 6, 8, 10, 9, 7, 6, 7, 6, 8, 4, 6};
public static double getMediatotal() {
return mediatotal;
}
public static void setMediatotal(double mediatotal) {
Media.mediatotal = mediatotal;
}
public static double mediat(double notasAlunos[]) {
double soma = 0;
for (int i = 0; i < 15; i++) {
soma = (soma + notasAlunos[i]) / 15;
mediatotal = soma;
}
return soma;
}
}
One way to access or change a variable private
would be to create methods get and set 'public' for that variable, i.e. the same way you did for the variable mediatotal
, see another example below
class Media{
private static double[] minhaVar;
public static void setMinhaVar( double[] novoValor ){
minhaVar = novoValor;
}
public static double[] getMinhaVar( ) {
return minhaVar;
}
}