Why doesn't my code print anything in stdout?

I am trying to calculate the student average:

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 );
    } 
}
+3
source share
5 answers

Here is a solution that uses two Scanner(as suggested in the previous answer).

  • Scanner stdin = new Scanner(System.in); scans user input
  • Scanner scores = new Scanner(stdin.nextLine()); browses a row containing grades

Please also note that it uses a much simpler and more understandable formula for calculating the average value.

        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);

Output Example:

Enter your average: Joe 1 2 3
Joe  2.0
+5
source

Since he is still sitting in the loop while, waiting for the team to exit the loop.

Here's Sun's tutorial on this . The course materials you received must also contain this information.

+4

( ) , Ctrl + D , . Ctrl + D , .

:

WM 1 2 3 6

Ctrl + D

+1

getline "exit". String.split Integer.valueOf , Java.

0

?

java.util.Scanner;

public class Average{

public static void main(String[] args)
{
    int mark = 0;
    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.println("Enter student name: ");
    String name = scan.next();

    System.out.println("Please enter marks one by one?");


    while(scan.hasNextInt()){

        int tempMark = scan.nextInt();
        mark += tempMark;
        countTotal+=1;

        System.out.println("If you are done with mark, type \"Done!\"");
    }

    avg = mark/countTotal;

    System.out.print( name + "  " + avg );
} 

}

0

Source: https://habr.com/ru/post/1743713/


All Articles