Modular programming in Java, called methods

1

I needed help putting the smallest and largest method to be "heard" in the main method. The logic of the program is to show the user the highest and lowest value of a vector .

CODE:

import java.util.Scanner;

public class L6ex3 {

    public static void main(String[] args) {
        Scanner e = new Scanner (System.in);
        int quantidade = 0;

        System.out.print("Quantos alunos serão cadastradas as idades?");
        quantidade = e.nextInt();

        int v[] = new int [quantidade];
        System.out.print ("Digite as idades");
        for (int i=0; i<quantidade; i++)
            v[i] =e.nextInt();



    }

    public int menorValor (int v[]){
        int menor =0;
        for (int i=0; i<v.length;i++)
            menor = v[i];

        for (int i=0; i<v.length; i++)
            if (v[i]<menor)
                menor =v[i];

        return menor;
    }

    public int maior (int v[]){
        int maior=0;
        for (int i=0; i<v.length;i++)
            if (v[i]> maior)
                maior = v[i];

        return maior;
    }

}
    
asked by anonymous 19.11.2015 / 03:58

2 answers

3

To call the methods menorValor() and maiorValor() you should put the static modifier in the methods.

public static int menorValor (int v[]){/*...*/}
public static int maiorValor (int v[]){/*...*/}

Then, in your main method, just call them normally:

   /* ... */
    System.out.println ("Maior valor: "+ maiorValor(v));
    System.out.println ("Menor valor: "+ menorValor(v));

I also suggest you change the code of the menorValor() method to the following:

public static int menorValor (int v[]){

    int menor =0;

    for (int i=0; i<v.length;i++)
        if(v[i] < menor)
            menor = v[i]

    return menor;
}
    
19.11.2015 / 04:17
1

Never assign any value, even if it is a ZERO. You do not know if the value is greater or less than what you typed.

  • I suggest that you always get the first value of the array as default, so it is part of that comparison.
  • Or, use the maximum or minimum value supported by the array type. (Integer.MIN_VALUE, Integer.MAX_VALUE)

If you are going to call inside the main function 'main', you should leave both methods static. If you do not want to leave static, put it inside a Class (in my opinion it would be ideal).

    
19.11.2015 / 12:28