Handling of JAVA arrays

Asked

Viewed 227 times

0

Good morning, I am developing a very simple stock system where the items will be stored in a matrix follows code:

package main;

import java.io.Console;
import java.util.Arrays;
import java.util.Scanner;

public class IncluirItem{
    public static void main(String[] args) {
        String[][] itens = new String[2][5];
        String[] campos = new String[7];
        int opcao = 0;
        int remover;
        int verificar = 0;
        int adcionar = 0;
        int tamanho = 2;
        
        Scanner sc = new Scanner(System.in);
        
        campos [1] = "Nome";
        campos [2] = "Codigo de barras";
        campos [3] = "quantidade";
        campos [4] = "validade";
        campos [5] = "data de entrada";
        
        do {
            System.out.println("\n\n### Sistema de estoque - simplificado ###");
            System.out.println("=========================================");
            System.out.println("      |     1 - Adcionar itens   |");
            System.out.println("      |     2 - Excluir itens    |");
            System.out.println("      |     3 - Mostrar itens    |");
            System.out.println("      |     0 - Sair             |");
            System.out.println("=========================================\n");
            
            System.out.println("Escolha uma opcao: ");
            opcao = sc.nextInt();
            System.out.print("\n");
            
            switch (opcao) {
            case 1:
                System.out.println("Cadastro de itens: ");
                //Adciona itens 
                for (int i = 0; i <2; i++) {
                    System.out.println("Adcionar item? ");
                    System.out.println("1 para sim \n2 para nao: ");
                    adcionar = sc.nextInt();
                    if (adcionar == 1) {
                        System.out.printf("%d. item \n", (i+1));
                        verificar = verificar + 1;
                        for (int j=0; j < 5; j++) { 
                            System.out.printf("%s ", campos[j+1]);
                            System.out.printf("= ", i,(j+1));
                            itens[i][j] = sc.next();
                            
                        }
                        System.out.printf("\n");
                    }
                    else {
                        break;
                    }
                }
                    
                break;
            case 2:
                //Remove itens
                System.out.println("Exclusao de itens: ");
                if(verificar > 0) {
                    for (int i = 0; i <2; i++) {    
                        System.out.printf("%d. item \n", (i+1));
                        System.out.printf("ID do produto= 00%d \n", (i+1));
                        System.out.printf("\n");
                    }
                }
                else {
                    System.out.println("Nenhum item listado!");
                }
                System.out.println("\nEscolha o numero do item a ser removido: \n");
                remover = sc.nextInt();
                for (int i = 0; i <2; i++) {
                    if(remover == 2) {
                    itens[i] = itens[i-1];
                    }
                }
                break;
            case 3:
                //Mostra itens
                if(verificar > 0) {
                    
                        for (int i = 0; i <2; i++) {    
                            if (verificar == 2) {
                            System.out.printf("%d. item \n", (i+1));
                            System.out.printf("ID do produto= 00%d \n", (i+1));
                            for (int j=0; j < 5; j++) { 
                                System.out.printf("%s ", campos[j+1]);
                                System.out.printf("= %s \n", itens [i][j]);
                            }
                            System.out.printf("\n");
                        }
                        else {
                                    itens = Arrays.copyOf(itens, tamanho - 1);
                                    verificar = 0;
                                    System.out.printf("%d. item \n", (i+1));
                                    System.out.printf("ID do produto= 00%d \n", (i+1));
                                    for (int j=0; j < 5; j++) { 
                                        System.out.printf("%s ", campos[j+1]);
                                        System.out.printf("= %s \n", itens [i][j]);
                                    }
                                    System.out.printf("\n");
                                    break;
                            }
                    }
                }
                else {
                    System.out.println("Nenhum item listado!");
                }
                
                break;
            default:
                System.out.println("Opção Inválida!");
                break;
            }
        } while(opcao != 0);
    }
}

My doubt is the following, I want to delete a position of the matrix, example: I recorded two items, in column one and column two of the matrix and I would like to remove column one from the list, as I perform this function, and another thing, I would like when I insert for the second time some item the matrix starts at the next empty possible, currently if I ask to insert a new item the matrix starts from the first position and so erases the elements already inserted.

3 answers

2

Arrays have a fixed size and there is no way to delete a specific position from it. The most you could do is set the position with null, but then you would have to check if the position is null before trying to use it.

But honestly, arrays are not the best way to do what you want. Let alone an array of strings. But let’s go for parts.


If an item can have several different information, group it into one class. Something like this:

public class Item {
    private String nome;
    private String codigoDeBarras;
    private int quantidade;
    private int validade;
    private String dataEntrada;

    public Item(String nome, String codigoDeBarras, int quantidade, int validade, String dataEntrada) {
        this.nome = nome;
        this.codigoDeBarras = codigoDeBarras;
        this.quantidade = quantidade;
        this.validade = validade;
        this.dataEntrada = dataEntrada;
    }

    public String getNome() {
        return nome;
    }

    // demais getters e setters, etc
}

I put the fields as String and int just as an example. I don’t know if the validity is actually a number - like "30" to say it’s worth 30 days, for example - or if it should be a date), and the date of entry could be a Date, or LocalDate, instead of String. But the code above is just to illustrate it.

I created a getter for the name, and you can do the same for the other fields. It is also interesting to read that to understand that you are not always obliged to create getters and setters for everything (but in the example below, let’s assume that I created all the getters).


Now that we have a class that represents the item, we can register. As it is dynamic (I can add and remove items at will), using array is not a good option, because as I said, it has fixed size. But the list of items can increase and decrease as the user type the options, so it is better to use a structure that can be modified as needed, such as a ArrayList. Would look like this:

public class CadastroItem {
    private List<Item> itens; // lista contendo os itens

    public CadastroItem() {
        // cadastro começa vazio - cria uma lista de itens sem nenhum elemento
        this.itens = new ArrayList<Item>();
    }

    public void adicionar(Scanner sc) {
        System.out.println("Adicionar item? ");
        System.out.println("1 para sim \n2 para nao: ");
        if (sc.nextInt() == 1) {
            sc.nextLine();
            System.out.printf("%d. item \n", itens.size());
            System.out.print("nome: ");
            String nome = sc.nextLine();
            System.out.print("código de barras: ");
            String codigoBarras = sc.nextLine();
            System.out.print("quantidade: ");
            int qtd = sc.nextInt();
            System.out.print("validade: ");
            int validade = sc.nextInt();
            sc.nextLine();
            System.out.print("data de entrada: ");
            String dataEntrada = sc.nextLine();
            // adiciona o item
            itens.add(new Item(nome, codigoBarras, qtd, validade, dataEntrada));
            System.out.println();
        }
    }

    public void remover(Scanner sc) {
        if (this.itens.isEmpty()) {
            System.out.println("Não há itens a serem removidos");
            return;
        }

        System.out.println("Itens existentes:");
        for (int i = 0; i < this.itens.size(); i++) {
            Item item = this.itens.get(i);
            System.out.printf("%d - %s\n", i, item.getNome());
        }
        System.out.println("\nEscolha o número do item a ser removido: ");
        int posicao = sc.nextInt();
        sc.nextLine();
        if (posicao < 0 || posicao >= this.itens.size()) {
            System.out.println("Posição inválida");
        } else {
            this.itens.remove(posicao);
        }
    }

    public void mostrar() {
        if (this.itens.isEmpty()) {
            System.out.println("Não há itens a serem mostrados");
        } else {
            System.out.println("Itens existentes:");
            for (int i = 0; i < this.itens.size(); i++) {
                Item item = this.itens.get(i);
                System.out.printf("%d - nome=%s, código de barras=%s, quantidade=%d, validade=%d, data de entrada=%s\n", i, item.getNome(),
                                  item.getCodigoDeBarras(), item.getQuantidade(), item.getValidade(), item.getDataEntrada());
            }
        }
    }
}

In some cases I called nextLine without assigning to any variable, because the methods that read numbers, such as nextInt, do not consume line break (the ENTER), then by calling nextLine soon after might not work properly (read here and here to better understand).

Notice that I have separated each operation into one method, leaving things a little more organized. Thus, the main would be:

CadastroItem cadastro = new CadastroItem();
Scanner sc = new Scanner(System.in);
while (true) {
    System.out.println("\n\n### Sistema de estoque - simplificado ###");
    System.out.println("=========================================");
    System.out.println("      |     1 - Adicionar itens  |");
    System.out.println("      |     2 - Excluir itens    |");
    System.out.println("      |     3 - Mostrar itens    |");
    System.out.println("      |     0 - Sair             |");
    System.out.println("=========================================\n");

    System.out.println("Escolha uma opcao: ");
    int opcao = sc.nextInt();
    sc.nextLine();
    System.out.println();
    if (opcao == 0)
        break; // se for zero, sai do while (nem testa as demais opções)

    switch (opcao) {
        case 1:
            System.out.println("Cadastro de itens: ");
            cadastro.adicionar(sc);
            break;
        case 2:
            // Remove itens
            System.out.println("Exclusao de itens: ");
            cadastro.remover(sc);
            break;
        case 3:
            // Mostra itens
            cadastro.mostrar();
            break;
        default:
            System.out.println("Opção Inválida!");
            break;
    }
}

Of course we can still improve. If a number is not entered, nextInt gives error and the program stops running. Then in class CadastroItem you could have a method that validates if you were typed a number in fact:

public class CadastroItem {
    ...

    private int lerNumero(Scanner sc, String mensagem) {
        while (true) {
            System.out.println(mensagem);
            try {
                return Integer.parseInt(sc.nextLine());
            } catch (NumberFormatException e) {
                System.out.println("Não foi digitado um número, tente novamente");
            }
        }
    }
}

So, you no longer need to have calls from nextLine shortly after nextInt, and would look like this:

public void adicionar(Scanner sc) {
    System.out.println("Adicionar item? ");
    System.out.println("1 para sim \n2 para nao: ");
    if (sc.nextInt() == 1) {
        sc.nextLine();
        System.out.printf("%d. item \n", itens.size());
        System.out.print("nome: ");
        String nome = sc.nextLine();
        System.out.print("código de barras: ");
        String codigoBarras = sc.nextLine();
        int qtd = lerNumero(sc, "quantidade:");
        int validade = lerNumero(sc, "validade");
        System.out.print("data de entrada: ");
        String dataEntrada = sc.nextLine();
        // adiciona o item
        itens.add(new Item(nome, codigoBarras, qtd, validade, dataEntrada));
        System.out.println();
    }
}

public void remover(Scanner sc) {
    if (this.itens.isEmpty()) {
        System.out.println("Não há itens a serem removidos");
        return;
    }

    System.out.println("Itens existentes:");
    for (int i = 0; i < this.itens.size(); i++) {
        Item item = this.itens.get(i);
        System.out.printf("%d - %s\n", i, item.getNome());
    }
    int posicao = lerNumero(sc, "\nEscolha o numero do item a ser removido: ");
    if (posicao < 0 || posicao >= this.itens.size()) {
        System.out.println("Posição inválida");
    } else {
        this.itens.remove(posicao);
    }
}

0

To remove column one, you should set the values of this column as 'null' or something like that, serving as an indication to yourself that this column is deleted. Already to add the values in the next column, it is possible to rotate the matrix to find the size and insert in the next index, it is possible to verify if the next position exists (Try catch is important in this case) Among other solutions... But in my opinion, you are at the perfect time to expand your horizons and understand Arraylist, because probably these functions are already native.

-1

For you to control the line that has already been registered an item is quite simple. Makes a counter variable starting from 0, Exp: int c = 0; In case 1 you put it like this: for (int i = c; i < (number of rows in the matrix); i++) {. And after I get out of it for: "for (int j=0; j < 5; j++) {}" you put c++; So you always go to a new line that has not been registered anything.

Browser other questions tagged

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