Issue
I try pass student names from main class to students class but I get error through runtime.
Main class is
public static void main(String[] args) {
Students students =new Students ();
Scanner in = new Scanner (System.in);
String [] name = new String [5];
for (int i =0; i <=4; i++){
System.out.print("Enter student name " + (i+1) + " : ");
name [i]= in.next();
}
students.SetData(name);
students.GetData();
}// Main
Students class is
public class Students {
private String Names [] = new String [5];
public void SetData (String [] Names){
for (int i=0 ; i <= Names.length; i++){
this.Names [i] = Names[i] ; //HERE is my error
} //for
} //SetData method
public void GetData (){
for (int i=0 ; i <= Names.length; i++){
System.out.println("Name of student " + (i+1) + " is " +Names[i]);
} //for
} //GetData mehtod
} //Students Class
Also how can I make my program check if user entered STRING or not ?
THANKS ALL
Solution
You should write
i < Names.length
in your loops, so they terminate one step earlier.
Names.length == 5
, i.e. one greater than the last valid index.
Nitpicks:
You shouldn't start variables with capital letters, they're reserved for class names. Using space before the []
array operator also looks weird.
Answered By - zslevi
Answer Checked By - Mary Flores (JavaFixing Volunteer)