gauche23
gauche23

Reputation: 67

How to add the user input in the loop?

I'm using array and loop, at the first input the user must enter the number of subjects and use the number to be the size of the array. Then on the loop, the program will accept "grades" on each subject.

I need to add those grades.

Please help.

import java.util.Scanner;
public class CaseStudy1 {
public static void main(String[] args) {

    Scanner inp = new Scanner(System.in);
    int numsub, grade, sum, ave;
    System.out.print("\nEnter number of subjects: ");
        numsub = inp.nextInt();

    int num[]=new int [numsub];

    int y=0;

        for(int x=0;x<numsub;x++) {
            y=y+1;

            System.out.print("\nEnter Grade in Subject [" + y + "] : ");
            grade = inp.nextInt();

            num[x]=grade;
        }

    }
}

Upvotes: 2

Views: 833

Answers (2)

BakaBoing
BakaBoing

Reputation: 26

you alreday got a variable for sum, just add this

sum+=grade;

into your for-loop after

num[x] = grade;

Upvotes: 1

Prabhakaran Ramaswamy
Prabhakaran Ramaswamy

Reputation: 26094

Include another variable called gradsum initialize with 0. Then add grade to gradsum while getting the grade values.

    int gradsum = 0;
    int y=0;
    for(int x=0;x<numsub;x++) {            
        y=y+1;
        System.out.print("\nEnter Grade in Subject [" + y + "] : ");
        grade = inp.nextInt();

        num[x]=grade;
        gradsum +=grade;
    }

   System.out.print(" Total of the Grade : "+gradsum );
   System.out.print(" Average : " + gradsum / numsub );

Upvotes: 0

Related Questions