Problems calculating on average in Java

3

I'm trying to make a program that calculates the average of 4 values.

Code:

    private void botao1ActionPerformed(java.awt.event.ActionEvent evt) {                                       
    // TODO add your handling code here:
    int n1 = Integer.parseInt(txt1.getText());
    int n2 = Integer.parseInt(txt2.getText());
    int n3 = Integer.parseInt(txt3.getText());
    int n4 = Integer.parseInt(txt4.getText());
    float notaf = (n1+n2+n3+n4)/4;
    res.setText(Float.toString(notaf));
}           
The problem is that when I have to use the result of the mean (notaf) it always comes as an integer (7.0, 8.0, 3.0) and does not come with the decimal numbers (7.5, 8.5, 3.5) where I went wrong?

Print the program:

(The average in this case should be 6.75)

    
asked by anonymous 05.02.2016 / 14:55

2 answers

4

The question already answers where the problem is. Note that the 4 notes are of type int . This type, as its name implies, only accepts integers. You have to change the type of the variables, and consequently the conversions. In case you should use float (you can discuss whether this type is also suitable, but will solve this exercise).

private void botao1ActionPerformed(java.awt.event.ActionEvent evt) {                                       
    // TODO add your handling code here:
    float n1 = Float.parseFloat(txt1.getText());
    float n2 = Float.parseFloat(txt2.getText());
    float n3 = Float.parseFloat(txt3.getText());
    float n4 = Float.parseFloat(txt4.getText());
    float notaf = (n1+n2+n3+n4)/4;
    res.setText(Float.toString(notaf));
}  

See running on ideone .

    
05.02.2016 / 15:01
3

Your problem is that all variables are of type int . If you do operations with integers only, the result is also integer, always ignoring (note, it ignores and does not round!) The decimal part.

If you do float notaf = (n1+n2+n3+n4)/4f; , to say that the operator is float would already be enough to work as you want.

    
05.02.2016 / 15:00