import java.util.Scanner;
public class Exercise1{
public static void main(String args[]){
int i=1,mark,totalmarks=0,highestmark=0;
Scanner input = new Scanner(System.in);
do{
System.out.print("Please enter the mark of student " + i + ":");
mark = input.nextInt();
while(mark<0 || mark>100)
{
System.out.print("Invaild! Please enter the mark of student " + i + ":");
mark = input.nextInt();
}
if(mark>highestmark)
highestmark = mark;
totalmarks += mark;
System.out.println("\n");
i++;
}while(i<=5);
System.out.println("\n\nHighest mark was: " + highestmark +
"\nAverage mark was: " + String.format("%.0f",totalmarks/5f));
}
}
In the exam marks for 5 students and determine the highest mark achieved along with the average of the marks to the nearest whole number. These marks should all be mathematical integers (whole numbers) within the range 0 to 100.
That paragraph above is the object on this code . I'm wondering that this code is weird logically.
if(mark>highestmark) highestmark = mark; when I saw this code, I thought all Numbers can be the mark like 1,2,3 to 100 but highestmark was initialized to 0 at first. how it is logical?
and last statement is (totalmarks/5f) why should I add 'f' at the end of 5? if I do not add f,an error outputs Please answer and explain those questions for me and thank you for your help
So highest mark is initialized to 0 because any mark will be higher than this. This means that the first time through the loop highestmark will be set to the first mark. If it was initialized to some number between 1 and 100 this could cause an incorrect output if all student marks were below the initial value for highestmark. It could even be set to -1 since 0 is a valid mark.
As for the last statement it uses 5f beacuse this casts the value to a float which is required for the division. If both values were integers java would perform an integer division which is not what you would want in this case.