-2

Hi so maybe i'm not seeing the where the error lies or maybe i don't know java well enough to know the execute order of operations but can someone explain to me why it is going wrong?

I'm trying to write a code to simply calculate the minimum grade you would have to get to get your wanted grade on ex a module in a course if you know your weight on your grades and one of the grades already.

//calculate minimum grades

public int calculateMinimumGradeWith2Ass1unknown (int Grade1, int Weight1, int WeightOnNext, int WantedOverAll){

    int val1 = Grade1*(Weight1/100);
    int estimate = WantedOverAll-val1;
    int Grade2 = estimate/(WeightOnNext/100);

    return Grade2;
}

I appriciate any kind of help :)

2 Answers2

4

First things first, in Java variable names are written with a lowercase character first (camelCase).

And class names are written with an uppercase character first (PascalCase).


Now to the exception. WeightOnNext / 100 is probably so small that, with integer division, it will be rounded to zero. And then you take estimate and divide it by 0 which yields the exception.

int Grade2 = estimate / (WeightOnNext / 100);

Just exchange all the ints with doubles and it will work.

Zabuzard
  • 25,064
  • 8
  • 58
  • 82
2

It seems like the problem is in the following part of the code:

int Grade2 = estimate/(WeightOnNext/100);

It would be helpful if you included sample values that cause that exception, but you need to be aware that ints doesn't support fraction part, they just cut it.

So, when WeightOnNext is less than 100, the (WeightOnNext/100) will always be cut to 0 and it will cause an exception when estimate/0; is performed.

For example:

WeightOnNext = 50;

50 : 100 = 0.5, but the fraction part (.5) is being cut, so there is 0 as a result of assigning to int variable.

You should consider using doubles for such operations to support fraction parts.


By the way, you should follow naming coventions of Java language - names of variables should be written in camelCase to make you code more readable for others and even for you, in the future.

Przemysław Moskal
  • 3,551
  • 2
  • 12
  • 21