how do you round up a double user input value in java? [closed]

Tags: , ,



Im a student whos making a simple grading system and Im struggling on how to do this

when I type in a specific number it go down to else bypassing my else-if statements the numbers are 98, 67, 98, 80 and 81 and i dont know why this happens

Here’s my code:

public static void main(String[]args) {

    double grade=0,tgrade=0,r;
    int gcount=0;


    for (int i = 0; i<5;i++) {

        grade   = Integer.parseInt(JOptionPane.showInputDialog(null, "Enter the grades "));
        tgrade = tgrade+grade;
        gcount++;
        System.out.println(gcount+". "+"grade: "+grade );

    }
    DecimalFormat c = new DecimalFormat("##.##");
    
    tgrade = tgrade/500*100;
    r = new Double(c.format(tgrade)).doubleValue();
    
    System.out.print("Total Grade: "+(tgrade)+"n");
    if      (r >= 95 && r <=100) {
        JOptionPane.showMessageDialog(null, "High Honor");
    }else if (r >= 90 && r <= 94){
        JOptionPane.showMessageDialog(null, "Honor");
    }else if (r >=85 && r <= 89) {
        JOptionPane.showMessageDialog(null, "Good");
    }else if (r>=80 && r<=84)   {
        JOptionPane.showMessageDialog(null, "Satisfactory");
    }else if (r>=75 && r<= 79) {
        JOptionPane.showMessageDialog(null, "Low pass, but certifying");
    }else {
        JOptionPane.showMessageDialog(null, "Low Failure");
    }
}

}

Answer

You variable r is double.

For example :

You have these numbers : 98, 67, 98, 80 and 81
The average is : 424/5 = 84.8

This value 84.8 doesnot fit both the condition you wrote :

if (r >=85 && r <= 89)
if (r>=80 && r<=84)

Hence it is going out.

You can use the below options.

FIRST Option : Don’t use the range as below :

if (r >= 95) {
    JOptionPane.showMessageDialog(null, "High Honor");
}else if (r >= 90){
    JOptionPane.showMessageDialog(null, "Honor");
}else if (r >= 85){
    JOptionPane.showMessageDialog(null, "Good");
}else if (r >= 80){
    JOptionPane.showMessageDialog(null, "Satisfactory");
}else if (r >= 75){
    JOptionPane.showMessageDialog(null, "Low pass, but certifying");
}else {
    JOptionPane.showMessageDialog(null, "Low Failure");
}

SECOND Option : If you are using range then frame the conditions like below :

if (r >= 95 && r <= 100) {
    JOptionPane.showMessageDialog(null, "High Honor");
}else if (r >= 90 && r < 95){
    JOptionPane.showMessageDialog(null, "Honor");
}else if (r >= 85 && r < 90) {
    JOptionPane.showMessageDialog(null, "Good");
}else if (r >= 80 && r < 85) {
    JOptionPane.showMessageDialog(null, "Satisfactory");
}else if (r >= 75 && r < 80) {
    JOptionPane.showMessageDialog(null, "Low pass, but certifying");
}else {
    JOptionPane.showMessageDialog(null, "Low Failure");
}

THIRD Option : If you need to round up then you can use Math.abs to extract the absolute value from the double r

Example :

Math.abs(r)


Source: stackoverflow