开发者

An array declared ouside the method(at class level), and assgned values inside a method doesn't work. Why?

开发者 https://www.devze.com 2023-03-30 14:34 出处:网络
*I made an array.. at the class level,but assigned it\'s values insi开发者_开发知识库de a method.. but for some reason.. it gave up an error..

*I made an array.. at the class level,but assigned it's values insi开发者_开发知识库de 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:

public int [] days = new int [7];

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:

public int [] days = new int[] {10, 15, 15, 15, 20, 20, 25};

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 it final:

private final int [] days = new int[] {10, 15, 15, 15, 20, 20, 25};


This statement is not valid to put in the class declaration:

days = new int[7];

Change it to an inline initialization:

public int[] days = new int[7];

Or put it in an initialization block:

{
    days = new int[7];
}

Or move it into the constructor.


public class VacationScale{

    public int [] days;

    days = new int [7];

That snippet appears to be causing your problem. You cannot assign a new value to days outside a method.

Perhaps you could try assigning it at the start of setVacationScale():

public void setVacationScale() {
    days = new int [7];
    days[0]=10;
    // ...
0

精彩评论

暂无评论...
验证码 换一张
取 消