What’s wrong with my code? I’m a beginner

Asked

Viewed 366 times

-3

I want to create an employee class with the specifications below, but I cannot return the show data method and the method calculate salary. It gives compilation errors when calling the methods, I wanted to know how to define their call, because there is something wrong. Thank you very much.

The official shall have:

  • Name, age, hourly wage and hours worked in the month.
  • Class attributes must be encapsulated.
  • there must be getters methods for everyone and setters for salary per hour and hours worked in the month.
  • There is a rule that the hourly wage should be between 10 and 200.
  • There is a rule that the hours worked in the month may not exceed 160 hours.
  • the method mostrarDados() is used to display all employee information in the console.
  • the method calcularSalario() returns the value of the employee’s salary. This amount is obtained by multiplying the employee’s hourly wage and the hours worked in the month.

Class Funcionario:

public class Funcionario {

      private String        nome;
      private int          idade;
      private int   salario_Hora;
      private int horas_trab_mes;


    public double getSalario_Hora() {
        return salario_Hora;
    }
    public void setSalario_Hora(double salario_Hora) {
        if (salario_Hora>10 & salario_Hora<=200){
            this.salario_Hora = salario_Hora;
        }

    }
    public double getHoras_trab_mes() {
        if (horas_trab_mes<=160){
            return horas_trab_mes;  
        }

    }
    public void setHoras_trab_mes(double horas_trab_mes) {
        this.horas_trab_mes = horas_trab_mes;
    }
    public String getNome() {
        return nome;
    }
    public int getIdade() {
        return idade;
    }

    public void mostrarDados(){
        System.out.println("O nome do funcionário é"+getNome());
        System.out.println("A idade do funcionário é"+getIdade);
        System.out.println("O número de horas trabalhadas do funcionário é "+horas_trab_mes);
        System.out.println("O salário por hora do funcionário é"+salario_Hora);
        }

    private double calcularSalario(){
        return salario_Hora*horas_trab_mes;
    }


}

Class Aplicacao:

public class Aplicacao {

    public static void main(String[] args) {

        Funcionario f= new Funcionario();
        f.setHoras_trab_mes(100);
        f.setSalario_Hora(100);

        System.out.println("Os dados do funcionário são:"+ f.mostrarDados();
        System.out.println("O salário do funcionário é:"+ f.calcularSalario();

        }
    }
}

When trying to compile, I get the following errors:

C:\Projetos\Funcionario\src\Aplicacao.java:9: error: ')' expected
        System.out.println("Os dados do funcionário são:"+ f.mostrarDados();
C:\Projetos\Funcionario\src\Aplicacao.java:10: error: ')' expected
        System.out.println("O salário do funcionário é:"+ f.calcularSalario();
C:\Projetos\Funcionario\src\Aplicacao.java:14: error: class, interface, or enum expected
}
3 errors
C:\Projetos\Funcionario\src\Funcionario.java:14: error: incompatible types: possible lossy conversion from double to int
            this.salario_Hora = salario_Hora;
C:\Projetos\Funcionario\src\Funcionario.java:25: error: incompatible types: possible lossy conversion from double to int
        this.horas_trab_mes = horas_trab_mes;
C:\Projetos\Funcionario\src\Funcionario.java:36: error: cannot find symbol
        System.out.println("A idade do funcionário é"+getIdade);
  symbol:   variable getIdade
  location: class Funcionario
3 errors
  • What’s the problem? What result did you get and what was expected?

  • 2

    First of all Welcome, our community is not a puzzle game of the 7 mistakes, also we are not here to solve course/college huahuahua exercises :-), please be as clear as possible, what is the error presented by your application ?

  • Actually I’m not from the IT area, but I like the idea of programming, I’m doing webinar and this exercise is on the list , what is to do in the description of the exercise, I wanted to know if there is some structural error, conceptual in my code, you know tell me? If you can help me I would appreciate it, it’s worth nothing not that. Just for real pleasure. Hugs.

  • 3

    Thiago, even for leisure, is no problem, as long as at least explain what went wrong or did not leave as expected. Where you will use the code is a detail, but objectivity is important, even in respect of the time of those who will help you. Here are some cool tips: [Ask]. Remember that you can [Dit] post and improve it anytime.

  • Thanks for the Bacco tips.

  • Damn, the question was closed and I was writing an answer. I disagree with the reason for closing, as it is enough to take a quick look at the code that the problems are easily perceived and are about compilation errors. There are also problems regarding the style adopted in the coding. I agree that this question is far from being one of our best questions, but I don’t think closure is justified. I voted to reopen.

  • I changed, is it not clear enough what I ask? I’m sorry I can’t ask technically, as I said earlier, I’m not from the area. Where do you think I should improve the question? Help me please.

  • @Bacco Can we reopen the question? If not, would like to understand the reason. It seems to me to be clear enough.

  • @ederwander The program features several silly compilation errors, typical of beginner thing. Being this clarified, we can reopen the question?

  • @Victorstafusa to me the problem is breadth, not clarity, but if you’re going to post the complete solution, we can. Let me know when you’re ready and I’ll participate in the reopening. Having people willing to do it, I’m not the one who’s going to stop you.

  • Thanks ederwander and Victorstafusa.

  • @Victorstafusa the question needs to be edited and demonstrate the errors, not everyone here has time to copy all the code in the question and keep checking the existing errors one by one, you understand me ?

  • @Victorstafusa I voted reopening and signaled for moderation reopen if you want, since you have answer, but let it be clear to the author that it is liberality your help, and not a "count on this always".

  • @Bacco Right. Thank you very much. Working here to avoid the problem no Soup for you, especially for those who are beginners.

  • 1

    @Victorstafusa the author guidelines were not in the sense of no Soup for you, were precisely to make possible the help. If only to leave it in the hand, would not have guided him to better describe the problems faced. Not always will people have the time necessary to take the code, analyze and compile, and to evaluate its complicates response, as it is an exercise of faith. I don’t know if you’ve really solved it, I don’t know if all the problems have been faced, I don’t know if a next visitor will be able to understand, and so on. But I voted to reopen it so as not to let the author down.

  • Thank you guys, sorry for the inconvenience , it was not the intention to bother anyone. Thank you to everyone who helped.

  • Thiagomarques is not bothersome no, we are only "fighting" to help in different ways. I prefer that you learn to fish, because you wouldn’t have the fish to give you ready, but it’s full of fish in the community. The @Victorstafusa had the good will to fish, clean the fish, cook and serve (I do not know if it was good or not pq I do not eat fish). What I would suggest is to taste this fish, but without failing to learn to fish in the next.

  • I marked Victor green already, he deserved it! I even understand your analogy of learning to fish, I do not refuse to learn to fish, but since there are facilitators to fish nowadays, since they exist and are supportive, why not facilitate learning? before to learn to fish we had to cross spatial and physical limitations, nowadays the fish jump on the bait :)

Show 13 more comments

2 answers

3


I put the description of the most obvious compilation errors in comments:

public class Aplicacao {

    public static void main(String[] args) {

        Funcionario f= new Funcionario();
        f.setHoras_trab_mes(100);
        f.setSalario_Hora(100);

        // Faltou um fecha parênteses.    
        System.out.println("Os dados do funcionário são:"+ f.mostrarDados();

        // Faltou um fecha parênteses.
        System.out.println("O salário do funcionário é:"+ f.calcularSalario();

        // Você está abrindo duas chaves e fechando três.
        }
    }
}
public class Funcionario {

      private String        nome;
      private int          idade;
      private int   salario_Hora;
      private int horas_trab_mes;


    public double getSalario_Hora() {
        return salario_Hora;
    }
    public void setSalario_Hora(double salario_Hora) {
        if (salario_Hora>10 & salario_Hora<=200){
            // O atributo salario_Hora é int, enquanto que você está tentando
            // atribuir-lhe um double. A linguagem java não permite isso diretamente
            // sem um cast porque iria perder precisão. Afinal como você colocaria
            // um número fracionário em algo que só aceita inteiros sem fazer
            // nenhuma conversão, adaptação ou arredondamento?
            this.salario_Hora = salario_Hora;
        }

    }
    public double getHoras_trab_mes() {
        if (horas_trab_mes<=160){
            return horas_trab_mes;  
        }

    }
    public void setHoras_trab_mes(double horas_trab_mes) {
        // Novamente, tentando colocar double no int.
        this.horas_trab_mes = horas_trab_mes;
    }
    public String getNome() {
        return nome;
    }
    public int getIdade() {
        return idade;
    }

    public void mostrarDados(){
        System.out.println("O nome do funcionário é"+getNome());

        // getIdade é um método, então faltou os parênteses.
        System.out.println("A idade do funcionário é"+getIdade);
        System.out.println("O número de horas trabalhadas do funcionário é "+horas_trab_mes);
        System.out.println("O salário por hora do funcionário é"+salario_Hora);
        }

    private double calcularSalario(){
        // Aqui você havia esquecido o ponto-e-vírgula,
        // mas você já editou isso na pergunta.
        return salario_Hora*horas_trab_mes;
    }


}

Most of these build errors are simple to solve, so I leave it to you. As for the problem of putting double in the int, it’s just you decide once and for all if the attribute is double or int and make the Setter parameters and the getter return value reflect your choice.

Finally, there are still other problems about coding style. Naming conventions dictate that method names, attributes and local variables should be composed of concatenated words without spaces, the first letter of each lowercase word and all other lowercase words, except for the first letter which must always be lowercase. Therefore, these identifiers are with a good nomenclature:

  • nome
  • idade
  • getNome
  • getIdade
  • calcularSalario

Already these have a bad nomenclature:

  • salario_Hora: Should be salarioHora
  • horas_trab_mes: Should be horasTrabalhadasMes - Don’t abbreviate words if you don’t have an excellent reason for it.
  • getSalario_Hora: Should be getSalarioHora
  • setSalario_Hora: Should be setSalarioHora
  • getHoras_trab_mes: Should be getHorasTrabalhadasMes
  • setHoras_trab_mes: Should be setHorasTrabalhadasMes

Done that, now there will still be some other more complicated compilation bugs, here they go:

    public double getHoras_trab_mes() {
        if (horas_trab_mes<=160){
            return horas_trab_mes;  
        }

    }

If the number of hours worked is less than or equal to 160, it will be returned. But, what if it is not? The answer is that this method is wrong and it should return the independent value of anything, the if is unnecessary.

The method mostrarDados is void. That is, it does not produce result. He himself is showing the output through the System.out.println rather than return some value. This behavior is incompatible with what is in your class Aplicacao:

    System.out.println("Os dados do funcionário são:"+ f.mostrarDados();

Instead, just call the mostrarDados() directly and itself will take care of the task of showing the data:

    f.mostrarDados();

And if you already have a method to show the data, then you don’t need to do it later:

    System.out.println("O salário do funcionário é:"+ f.calcularSalario();

After all, if you have a method that serves to show the data on the console, it makes more sense to put it inside.

With that, only these two rules are missing:

  • There is a rule that the hourly wage should be between 10 and 200.
  • There is a rule that the hours worked in the month may not exceed 160 hours.

And you are on the right track, the ideal is to do this within the setters. When these restrictions are satisfied, it is easy, just set the value of the fields and ready. When not satisfied, you can make three possible paths:

  • Do nothing - that’s what you’re doing at the moment.
  • Write something on System.out.println saying that the method refused to set the value.
  • Throw an exception - what is the right treatment for robust systems, but you are at a level too beginner to be able to handle this case, since exception treatment is something that is at a significantly more advanced level than what you are at the moment.

I hope I’ve helped you.

  • Thank you very much Victor, clarified a lot. Thanks even for the help, I think the staff does not like who is starting, I do not know.... , Hugs.

  • 1

    @Thiagomarques Well, if my answer helped you and solved your problem, mark it as accepted by clicking on the green V that is just below the voting number. If you still have any questions, or you think something important is missing, post a comment. As for the community not liking beginners, this is a half-truth. In fact, the community does not like questions with some types of problems in their elaboration that can hinder the production of answers, occurs that beginners still do not have the necessary experience to elaborate questions that do not have such problems.

  • There’s the green Victor! , very good comment as it is inherent to beginner status that condition of crafting perfect questions is somewhat complicated, thanks for the empathy. If you need help with statistics, we are ae :) hugs!.

0

System.out.println("Os dados do funcionário são:"+ f.mostrarDados());
System.out.println("O salário do funcionário é:"+ f.calcularSalario());

At a glance there are many incomplete calls; missing check there ...

  • Thanks John-Jones.I’ll check, hugs.

Browser other questions tagged

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