Problems assigning values to variables in an object

Asked

Viewed 684 times

4

I need to pass variable data to another class called Fila.java. There I have a vector of the type that receives objects, so in the main class I created an object that I initialized as follows :

public class Dados{
    int menu = 20,i=0; 
    String produto;
    int Quantidade=0;
    float ValorUn=0,Desconto=0,AliquotaICMS=0;
    String Obs;     
}

public static void main(String[] args) {        
        BancoDeDados db = null;
        Dados da = new Dados;
        da.menu = 20;
}

However intendente the way I initialize it, generates error when compiling

If I start like this :

Dados da;

It says that the variable was not initialized, if I assign the value NULL, says it’s pointing to a null pointer, how to solve?

Classe Fila.java        
public class Fila {
    public Fila() {     

    }

    int inicio, fim, numelem,tamanho;
    Object array[];
    String elem;//string

    Fila(int tam){
        this.inicio = 0;
        this.fim = 0;
        this.numelem = 0;
        this.tamanho=tam;
        this.array = new Object[tam];
    }

    public boolean vazia(){
       if(numelem==0)
           return true;
           return false;    
    }

    public void inserir(Object elem){       
        array[fim]=elem;
        numelem++;
        fim++;
        if(fim==tamanho)
        fim=0;
        System.out.println(array[0]);
    }
    public Object remover(){
        Object temp=null;
        if(!vazia()){
            temp=array[inicio];
            array[inicio]=null;
            inicio++;
            numelem--;
            if(inicio==tamanho)
                inicio=0;
        }
        else
            System.out.println("Fila vazia");
        return temp;
    }


    public void AumentarVetor() {       
        tamanho = (tamanho/2)*3;                
    }                               
}

Main class :

import BancoDeDados.Dados;

public class Main {

    public static class Dados{

        int menu = 20,i=0; 
        String produto;
        int Quantidade=0;
        float ValorUn=0,Desconto=0,AliquotaICMS=0;
        String Obs;

        public Dados(){
              //também á uma boa idéia inicializar os valores das variáveis dentro do construtor
            }

    }
    public static void main(String[] args) {
        // TODO Auto-generated method stub      
        //BancoDeDados db = null;
        //BancoDeDados.main(args);
        Dados da = new Dados();
        da.menu = 20;
        da.produto = "Teste";
        Fila f = new Fila();

        da.menu = 10;

        f.inserir(da);              
    }
}
  • You should describe the error obtained when compiling. Note that apparently your code is wrong. The most method is outside the class. Apparently scattered in the archive.

  • Good evening, It shows following message : "The local variable da may not have been initialized. " But I don’t know how I should boot it.

2 answers

1

You need to create a constructor method, the constructors are responsible for creating the object in memory, ie instantiating the class that has been defined. They are mandatory and are declared this way:

public class Dados{

    int menu = 20, i = 0; 
    String produto;
    int quantidade = 0;
    float valorUn = 0, desconto = 0, aliquotaICMS = 0;
    String obs;

    public Dados(){
        //também é uma boa idéia inicializar os valores das variáveis dentro do construtor
    }
}

A class can have multiple constructors and they can receive no or multiple parameters, and in the class main you must instantiate the object like this:

Dados da = new Dados();
  • Part of the problem has been solved, thank you very much. Now it gives error when inserting in queue Exception in thread "main" java.lang.Nullpointerexception At Fila.insert(Fila.java:40) at Main.main(Main.java:36)

  • how is the code of the Fila class?

  • I added the class in the description of the problem.

  • 2

    "you need to create a constructor method, ""They are mandatory" is not entirely true. It is not mandatory to define a constructor, as the compiler will create one without parameters if none is defined.

0

Let’s break the problem in pieces.

  1. The class BancoDeDados is not relevant to the problem. Nothing is done with it on Main.
    Thus, the problem is in the following 2 lines:

Error code:

Dados da = new Dados;
da.menu = 20;
  1. The Data class is initialized as Dados da = new Dados(); There is a syntax error. I assume the class Dados has only 1 constructor, the empty constructor (no arguments).

Somewhere in the code of the Data class, I assume to exist:

public Dados()
{
    /*Faz alguma coisa aqui? Talvez aqui inicialize a Fila?*/
}
  1. Confirm that the Queue is initialized with the correct constructor. Fila testeFila = new Fila(5);. Please note that new Fila(5); calls the constructor of 1 argument:

The builder who created:

Fila(int tam){
    this.inicio = 0;
    this.fim = 0;
    this.numelem = 0;
    this.tamanho = tam;
    this.array = new Object[tam];
}

Call Fila testeFila = new Fila();, the so-called builder is:

public Fila() {
}

And the array is not initialized.


One of these steps was the problem?


Fila is a Class. This class has a field Object array[];.

This object is not initialized by default. The line the instance is in the constructor:

Fila(int tam){
    this.inicio = 0;
    this.fim = 0;
    this.numelem = 0;
    this.tamanho = tam;
    **this.array = new Object[tam];**
}

That is, it is necessary that the code reaches this line so that the object array is initialized.

Fila(int tam) is a class builder Fila. Takes as parameter an integer, and executes the 5 lines of code that are in the above snippet.

On your Main, declares the queue as

Fila f = new Fila();

This will not call the builder who created above, but the empty builder.

Still in your class Fila:

public Fila() {     
        /*Este é o código que executa ao invocar Fila f = new Fila();*/
}
  • Good afternoon, I put the Main class in the description of the problem, the problem is that I cannot insert it into the array as shown in Main. Note : Yes, it has an empty constructor.

  • So part of the problem is the instantiation of the Queue. I’m going to edit the answer a little for clarity; see point 3.

Browser other questions tagged

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