user1458650
user1458650

Reputation: 9

Adding Numbers Entered by for-loop

My objective is to add numbers, entered by the user, using a for-loop .

Here is my code:

import java.io.*;
class Student {
    public static void main (String args[]){
    int mks=0, i=0 ,percnt=0;
    BufferedReader br = new BufferedReader (new InputStreamReader(System.in));
        try {
            System.out.println("Enter Marks Of Student ");      

            for (i=0;i<=4;i++){
            mks= Integer.parseInt(br.readLine());
            mks=mks+i;
            }
        }catch (Exception e) {}
        percnt=mks/5;

        System.out.println("GRAND TOTAL = "+mks+ " PERCENTAGE"+percnt);
    }
}

I am getting the marks entered last + 4 with this code.

Upvotes: 0

Views: 476

Answers (4)

Chris Dargis
Chris Dargis

Reputation: 6043

"my objective is to add the numbers entered by the user using for loop"

You need to accumulate each integer entered by the user:

mks += Integer.parseInt(br.readLine());

"i m getting marks entered last + 4 with this code"

This is because your code:

mks= Integer.parseInt(br.readLine());  // Get the integer the user entered
mks=mks+i;        // Add i (which in the case of the last iteration is 4)

is setting the value of mks everytime the loop restarts. Also, if you are trying to count all of the numbers the user enters, there is no need to add the loop counter i to the accumulator variable mks

Upvotes: 1

Lion
Lion

Reputation: 19027

Your code should be like.

int mks=0, i=0 ,percnt=0;
BufferedReader br = new BufferedReader (new InputStreamReader(System.in));
try {
    System.out.println("Enter Marks Of Student ");

for (i=0;i<=4;i++){
    mks+=Integer.parseInt(br.readLine())+i;
    //mks=mks+i;
}
}catch (Exception e) {}
percnt=mks/5;
System.out.println("GRAND TOTAL = "+mks+ " PERCENTAGE"+percnt);

Upvotes: 0

theglauber
theglauber

Reputation: 29625

You are reinitializing your accumulator (mks) variable with each loop iteration.

You need to define it once, outside of the loop, with value of zero, then add to it with each loop iteration.

Also, get rid of mks=mks+i

Lastly, catching Exceptions and ignoring them doesn't do you any good. You should at least display an error message when there is an exception. Otherwise, just declare the exception in a throws clause, and let it propagate (i.e. let it terminate the program).

Upvotes: 0

Thunderforge
Thunderforge

Reputation: 20575

Every time the "mks= Integer.parseInt(br.readLine());" is called, it overwrites the previous values of mks. So the last time you run it, you get the last line entered +4 (the value of i at the time).

If you're wanting to sum the value of all the loaded marks, you should make a new variable that doesn't get overwritten. Or alternatively, you could do

mrks = mrks + Integer.parseInt(br.readLine()) + i

Upvotes: 0

Related Questions