CODE
class DistributeChocolatesForStudents
{
public static void main(String arg[])
{
int number_of_students = 5;
int number_of_chocolates = 15;
if( number_of_students <= 0 )
{
System.out.println("Chocolates can not be distributed since there are no students or negative number of students.");
}
else
{
int number_of_chocolates_per_student = number_of_chocolates / number_of_students;
System.out.println("Every student gets " + number_of_chocolates_per_student + " chocolates.");
}
}
}
Every student gets 3 chocolates.
In this program, we are distributing the chocolates among students. If we divide the number of chocolates by number of students, then we can find how many chocolates each student gets. But if there are no students, then we will get a '/ by zero' ArithmeticException
. To prevent this we are checking that the number of students is not zero. We are also checking that the number of students can not be less than zero. To perform these two checks we are using the less than or equal (<=
) operator.
number_of_students
from 5
to 0
and see what will be output.number_of_students
from 5
to -4
and see what will be output.number_of_students
from 5
to 7
and see that the number of chocolates is 2
. But 7 * 2
is not 15
but 14
. Please note that the extra 1
chocolate is missed due to rounding which occurs when we divide an integer with another integer.