Reputation: 38
I'm trying to solve this exercise:
Write a program called GradesAverage, which prompts user for the number of students, reads it from the keyboard, and saves it in an int variable called numStudents. It then prompts user for the grades of each of the students and saves them in an int array called grades. Your program shall check that the grade is between 0 and 100. A sample session is as follow:
Enter the number of students: 3
Enter the grade for student 1: 55
Enter the grade for student 2: 108
Invalid grade, try again...
Enter the grade for student 2: 56
Enter the grade for student 3: 57
The average is 56.0
But, in my file, this is how the program works (pay attention to the "student"):
Enter the number of students: 3
Enter the grade for student10 55
Enter the grade for student20 56
Enter the grade for student30 57
Can you see the 10, the 20 and 30? Instead of showing student1
, student2
and student3
, it shows student10
, student20
and student30
.
Here is my code:
import java.util.Scanner;
class GradesAverage {
public static void main (String[] args) {
Scanner miScanner = new Scanner(System.in);
System.out.println("Enter the number of students: ");
int numStudents = miScanner.nextInt();
int numberGrades[] = new int[numStudents];
int averageGrade = 0;
for (int i = 1; i <= numStudents; i++) {
System.out.println("Enter the grade for student" + i + numberGrades[numStudents - i]);
int grade = miScanner.nextInt();
averageGrade += grade;
if (grade < 0 || grade >100) {
System.out.println("Invalid grade, try again...");
break;
}
}
double average = averageGrade/numStudents;
System.out.println("The average is " + average);
}
}
Upvotes: 1
Views: 902
Reputation: 17132
Change
System.out.println("Enter the grade for student" + i + numberGrades[numStudents - i]);
to
System.out.println("Enter the grade for student " + i + ":");
That extra 0 is outputted due to the extra numberGrades[numStudents - i]
.
Why exactly zero ? Because numberGrades
is an array; when initializing an array, it initializes its elements to their default types' values. (In this case, it's an array of int
s, so all of its elements are initialized to 0)
PS: That number that you see here after the colon (in this case 55):
... student 1: 55
is actually an input, not a sysout.
Upvotes: 2
Reputation: 926
System.out.println("Enter the grade for student" + i + numberGrades[numStudents - i]);
Its printing out this Enter the grade for studenti
numberGrades[numStudents - i]
These are not being added before printing, its printing each item.
Upvotes: 1