*I made an array.. at the class level,but assigned it’s values inside a method.. but for some reason.. it gave up an error..
then when i did the array declaration & assignment inside of the same method..
everything functioned smoothly!! Why is that? I declared the array at class level.. so it has class scope right?? so why can’t i assign it values inside a method?? I’m utterly confused :/ *
public class VacationScale{
public int [] days;
days = new int [7];
public void setVacationScale(){
days[0]=10;
days[1]=15;
days[2]=15;
days[3]=15;
days[4]=20;
days[5]=20;
days[6]=25;
}
public void displayVacationDays(int yearsOfService){
if(yearsOfService >=0 && yearsOfService<=6){
System.out.println("the years of the service of the employee is "
+yearsOfService+ " and hence the employee is eligible to :"
+days[yearsOfService]+ " holidays");
}
else if(yearsOfService >6){
System.out.println("the years of the service of the employee is "
+yearsOfService+ " and hence the employee is eligible to :25"
+" holidays");
}
else{
System.out.println("invalid number of years of service");
}
}
}
The error that shows up on the command prompt is– identifier expected
The line
days = new int [7];is invalid code outside of a method. Instead write:which will both declare and initialize the array.
Beyond this, there is no need for your
setVacationScale()method, since it appears to be hardcoded. Instead, you can initialize the array to have these values:To give a few more tips, it’s unwise to expose access to the array outside the class if it’s only used by the class’s methods – if this is the case change its access modifier to
private. And as long as the array is only initialized once, it’s good form to make itfinal: