AM new to Programming, I need help with my Program
Hello,
I'm in a beginning class for java programming and I can't seem to understand how to use the array and for loop together. I keep getting this message when I compile my program.
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 5
at GradeList.main(GradeList.java:40).
Here is my Program,
import java.util.*;
public class GradeList2
{
// This Program accumulates and create grades and class average
public static void main(String[] args)
{ // Tell the user this program calculates grades for a class
System.out.println("This program calculates grades for a class of students");
// input scanner
Scanner input = new Scanner(System.in);
// declare variables
int numStudents;
int totalpts;
int studentpts;
int k;
double percent;
char grade;
// ask and get users input number of students and total possible points
System.out.print("Please Enter the Number of students: ");
numStudents = input.nextInt();
System.out.print("Please enter the Total Possible Points: ");
totalpts = input.nextInt();
// tell user to enter each students points
System.out.println("Please Enter Each Students Points");
// declare array
int [] studentList = new int [numStudents];
// input for loop
for (k=1; k <= numStudents; k++)
{
System.out.print("Points for Student " +k+ " ");
studentList[k] = input.nextInt();
// If Points is greater that Total_Points, tell the user Invalid Student Points
while (studentList[k] > totalpts || studentList[k] < 0)
{ System.out.println("Sorry that is over the total possible point, try again");
// Get students total points again
System.out.print("Points for student " +k+ " ");
studentList[k] = input.nextInt();
}
}
System.out.println(" ");
// print formatted output for headings
String formathd= "CLASS OF " +numStudents+ " STUDENTS POINTS PERCENT GRADE ";
// format lines
String formatDashes= " ------ ------- ----- ";
// show variables and lines
System.out.println(formathd);
// Print Dashes
System.out.println(formatDashes);
// calculate percent and grade for each student points and store into percent array
for (k=1; k < numStudents; k++)
{
// Get Student Points
System.out.print("Student"[k]);
percent = ((studentList[k])/(totalpts)) *100;
if (percent >= 90.00){
grade = 'A';
}
else if (percent >= 80.00)
{
grade = 'B';
}
else if (percent >= 70.00)
{
grade = 'C';
}
else if (percent >= 60.00)
{
grade = 'D';
}
else
{
grade= 'F';
}
String format= "%25s %11d %11.2f %9c";
System.out.printf(format, studentList[k], percent, grade);
}// End of for loop
} // end of main method
} // end of class
Re: AM new to Programming, I need help with my Program
The array indices go from 0 to numStudents - 1, not 1 to numStudents
See this http://docs.oracle.com/javase/tutori...ts/arrays.html