Coco
Coco

Reputation: 45

JAVA Trouble printing the correct amount of grades that the user asked for using one dimenstional array and methodss

I'm basically asking the user to enter the amount of grades he would like to enter and those grades would be stored in an array. I would ask the user "Please enter the number of grades". If the user has entered '3' for example. Then the he would be asked to input data for 3 grades. A message would pring "Enter grade 1: " "Enter grade 2: " "Enter Grade 3: " etc. I didn't have any trouble writing the code but obviously it's not correct.

When I enter 3 for example for the number of grades, the program starts my printing "Enter Grade 0:" and then goes on to print 4 grades. enter image description here

Here's my code:

I feel like I need to somehow involve the array length? Any help would greatly appreciated. :)

Upvotes: 0

Views: 113

Answers (3)

Floam
Floam

Reputation: 704

You should have i< numOfGrades since you are starting at 0. Also add 1 to i in the print statement to start at grade 1 :).

for (int i = 0; i < numOfGrades; i++) {

        System.out.println("Enter grade " + (i+1) + ": ");

        mogrades[i] = NumberReader.readPositiveDouble(input, 
                    "Enter grade: ", "Invalid data entered");

I also agree with the other posters here. You should be using mogrades.length. This makes it clear to the reviewer that you are likely going to be working with the array, mogrades.

 for (int i = 0; i < mogrades.length; i++) {

            System.out.println("Enter grade " + (i+1) + ": ");

            mogrades[i] = NumberReader.readPositiveDouble(input, 
                        "Enter grade: ", "Invalid data entered");

Upvotes: 1

rpy
rpy

Reputation: 4013

You have numOfGrades slots with your array . So, this is 0,1...numOfGrades-1. However, you loop upto numOfGrades due to

for (int i = 0; i <= numOfGrades; i++)

You should use

for (int i = 0; i < numOfGrades; i++)

to not write beyond the end of your array.

Upvotes: 0

Guy
Guy

Reputation: 50809

Array indexes are from 0 to size - 1. When i equals to numOfGrades in the loop you are out of the array. Change i <= numOfGrades to i < numOfGrades or better to i < mogrades.length

for (int i = 0; i < mogrades.length; i++) {
    System.out.println("Enter grade " + i + ": ");
    mogrades[i] = NumberReader.readPositiveDouble(input, "Enter grade: ", "Invalid data entered");
}

Upvotes: 2

Related Questions