I’m trying to calculate the average of a student’s marks:
import java.util.Scanner;
public class Average
{
public static void main(String[] args)
{
int mark;
int countTotal = 0; // to count the number of entered marks
int avg = 0; // to calculate the total average
Scanner Scan = new Scanner(System.in);
System.out.print("Enter your marks: ");
String Name = Scan.next();
while (Scan.hasNextInt())
{
mark = Scan.nextInt();
countTotal++;
avg = avg + ((mark - avg) / countTotal);
}
System.out.print( Name + " " + avg );
}
}
Here’s a solution that uses two
Scanner(as suggested in my previous answer).Scanner stdin = new Scanner(System.in);scans user’s inputScanner scores = new Scanner(stdin.nextLine());scans the line containing the scoresNote also that it uses a much simpler and more readable formula for computing the average.
Sample output: