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.
Scanner stdin = new Scanner(System.in);
System.out.print("Enter your average: ");
String name = stdin.next();
int count = 0;
int sum = 0;
Scanner scores = new Scanner(stdin.nextLine());
while (scores.hasNextInt()) {
sum += scores.nextInt();
count++;
}
double avg = 1D * sum / count;
System.out.print(name + " " + avg);
Sample output:
Enter your average: Joe 1 2 3
Joe 2.0
Because it's still sitting in the while loop, waiting for an instruction to break out of the loop.
Here's a Sun tutorial on the subject. The course materials you got should also contain this information by the way.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With