Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is my code not printing anything to stdout? [closed]

Tags:

java

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 );
    } 
}
like image 716
wam090 Avatar asked Jan 18 '26 00:01

wam090


2 Answers

Here's a solution that uses two Scanner (as suggested in my previous answer).

  • Scanner stdin = new Scanner(System.in); scans user's input
  • Scanner scores = new Scanner(stdin.nextLine()); scans the line containing the scores

Note 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
like image 182
polygenelubricants Avatar answered Jan 20 '26 13:01

polygenelubricants


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.

like image 22
BalusC Avatar answered Jan 20 '26 14:01

BalusC



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!