Pass array as parameter

Asked

Viewed 802 times

1

I have a question about arrays. So I have the following code:

public static void main(String[] args) {

    //Objetos.....

    ColeçãoCidades ListaCidades = new ColeçãoCidades();

    //Adicionar regiões
    Scanner sc = new Scanner(System.in);

    System.out.print("Digite quantas regiões serão criadas: ");
    int quant = sc.nextInt();

    Scanner sc3 = new Scanner(System.in);

    Regiao[] regioes = new Regiao[quant];
    for (int i=0;i<quant;i++){
        System.out.print("\nInforme o nome da região: ");
        String reg = sc3.next();
        System.out.print("\nINforme o código da região: ");
        int cod = sc3.nextInt();
        regioes[i]= new Regiao(cod,reg);
    }


    // Menu
    MenuCidade(ListaCidades);
    }


    private static void MenuCidade(ColeçãoCidades lista) {

    Scanner sc2 = new Scanner(System.in);
    int op;

    do{
        // Apresentar as opções
        System.out.print("\n\tSegue abaixo as opções disponíveis para o menu cidade...\n\n" + 
                        "1) Adicionar cidade\n" + 
                        "2) Pesquisar Cidades Por Região\n" + 
                        "3) Pesquisar Cidades Por Estado\n" + 
                        "4) Pesquisar Cidades Por País\n" + 
                        "5) Pesquisar Cidades com Mais de 'X' habitantes\n" + 
                        "6) Remover cidade por nome\n" +
                        "7) Remover cidade por código\n" +
                        "8) Pesquisar Cidades Com Nível De Complexidade Maior Que 'X'\n" +
                        "0) Sair\n");
        System.out.print("Digite uma opção: ");
        op = sc2.nextInt();

        // Verificar se o valor dado está entre as opções válidas...
                    if((op < 0) || (op > 8)){
                        System.out.println("\n\tOpção inválida - Tente novamente");
                    }else
                    switch(op){

                    case 1: Cidade cid = new Cidade();
                            Cidade(cid);
                            lista.adicionarCidade(cid);
                            break;

                    case 2: System.out.print("NOme da região: ");
                            String regiao = sc2.nextLine();
                            lista.pesquisaCidadesPorRegião(regiao);
                            break;

                    case 3: System.out.print("NOme do Estado: ");
                            String estado = sc2.nextLine();
                            lista.pesquisaCidadesPorEstado(estado);
                            break;

                    case 4: System.out.print("Nome do País: ");
                            String pais = sc2.nextLine();
                            lista.pesquisaCidadesPorPaís(pais);
                            break;

                    //case 5:

                    case 6: System.out.print("Nome da cidade: ");
                            String nome = sc2.nextLine();
                            lista.removeCidadePorNome(nome);
                            break;

                    case 7: System.out.print("Código da cidade: ");
                            int codigo = sc2.nextInt();
                            lista.removeCidadePorCódigo(codigo);
                            break;

                    //case 8:

                    }
    }while (op!=0);

}   


    public static void Cidade (Cidade cid){
    Scanner sc = new Scanner(System.in);

    //Apresentar o menu cadastro...
    System.out.println("\n\tCadastro de nova cidade");

    System.out.print("\nCódigo da cidade: ");
    int codigo = sc.nextInt();

    System.out.print("\nNome da cidade: ");
    String nome = sc.nextLine();

    System.out.print("\nPopulação: ");
    double populacao = sc.nextDouble();

    System.out.print("\nEstado: ");
    String estado = sc.next();

    System.out.print("\nPaís: ");
    String pais = sc.next();

    System.out.print("\nRegião: ");
    String reg = sc.next();
    //pesquisaRegiao(Regiao[] array,reg);

    System.out.println("\n\tCadastro realizado com sucesso!!!");

}


    //private static void pesquisaRegiao(Regiao[] array, String reg) {


    }
}
  • That’s all you want? private static void pesquisaRegiao(Regiao[] array, String reg) {. Ah, I just saw that you’re passing a variable that doesn’t even exist in the method. The code is very confusing, so not only for you, but for everyone who’s reading it, it’s hard to do anything right.

  • So I thought I should create the regions before, so when I went to create the cities the regions would already exist. There is no way to pass this array to the method?

  • 1

    Is the code complete? I see now that part of the mess is because relevant parts are missing. Or code is completely meaningless.

  • There’s only one other thing I can’t comment on.

  • You can [Dit] the question and put in it.

  • Ta complete now(the Main class).

  • @bigown did you rollback in the last issue? Well you had noticed that they removed parts of the code from it, deliberately and thought it was the OP.

  • Yes, she destroyed the AP edition.

  • @Willian.as The answer solved the problem? Do you think you can accept one of them? See [tour] how to do this. You’d be helping the community by identifying the best solution. You can only accept one of them, but you can vote for anything on the entire site.

Show 4 more comments

1 answer

2


The code is quite confusing and would need to make several changes to solve the problem. The first is to match the signature of the method that will receive the regions, missed to put the type:

 private static void pesquisaRegiao(Regiao[] regioes, String regiao) {

The other necessary amendment is to array with the regions for the method that needs to use it:

public static void Cidade(Cidade cid, Regiao[] regioes) {

That’s what I’d call it:

Cidade(cid, regioes)

You’d have to do the same thing when you go on the menu.

Do you have a static method with the same class name? Don’t do this.

Try to avoid abbreviations in the names of things, affects readability and brings no real benefits.

For the Java style, the most certain in this case may be to play the variable regioes for the class and access them from all methods where it is needed without having to go through the methods.

I thought I’d write an example of how to do this, but to do it right I’d have to rewrite the whole code, which I don’t think is the point. And I don’t know if it would be a good thing, since you’re struggling in the basics, starting to structure code into classes seems to be a step that you’re not ready to take yet.

First try to organize the code in simpler methods, that only do one thing, which communicate more clearly. Remember that the code is not something magical, it is a text that the computer must understand, but mainly that a human must read naturally. Before coding it is necessary to understand the problem and find the correct structure to represent it in the code.

A tip: when accurate post comments means that there should be another method. There are comments that are simply unnecessary. Comments are rarely necessary in fact and certainly should not be used for what was in this code.

Just take things one step at a time. In fact, you might want to start over by doing one thing at a time. You can ask around here every step you take, then it’s easier to help. It is very difficult to help when the code is poorly structured deep. I strongly suggest following this suggestion to get qualified help. In new questions here describe the problem and what you started to do, one step at a time. It is important to make a clean code and cohesive.

  • I really have to learn a lot yet, programming is not very my area because I study Computer Networks and I’m only paying the POO discipline. But I want to thank you very much for your help, because you solved the problem. And as you said, I will try to fix this code that is very confusing. Thanks.

  • He managed to do a lot of things. Now he needs to learn what’s harder, to do organized :) It’s very important, it’s not freshness.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.