Search code examples
javaarraysmethodsintegerjoptionpane

Integer initializing and method error


I'm having trouble with the following... I've removed the none important part of the code so it's not as confusing. All other symbols/variables have been defined and or initialized already.

Basically what I'm trying to do is this:

numsalchange is a seperate method that is determining in a loop if values in the indsaldif array are 0. If they are, it's of course incrementing change.

Change is later being sent to the report method to be displayed. I've tried it several different ways with values that will and will not definitely equal 0. However, each time change is outputted as 0, when I know it should definitely be something else.

I've tried just declaring the change as

int change;

And then setting it as zero in the method, but it will not let me send it to the method without being initialized in the main.

I have a feeling it is being displayed in the report method as 0, because it is being intialized as zero and sent to report as 0 and not the updated value.

public static void main blah(String[] args){

int change = 0;
numsalchange (userinput, change, indsaldif);
report (userinput, oldsalary, newsal, indsaldif, change);


public static void numsalchange(String[] userinput, int change, double[] indsaldif){



    for ( int i=0; i<userinput.length; i++){

        if(indsaldif[i] != 0){
            change++;}}}
    public static void report(String[] userinput, double[] oldsalary, double[] newsal, double[] indsaldif, int change){

            DecimalFormat twoDigits = new DecimalFormat("0.00");
            double saldiff = 0;
            for( double i : indsaldif) {
                    saldiff += i;
                }
            String toString;                        
            StringBuilder sb = new StringBuilder(64);
            sb.append("PB Incorporated Salary Report \n");
            for (int i = 0; i < userinput.length; i++) {
             sb.append("---------- \nEmployee:"+ userinput[i] + "\nOld Salary: $"+ twoDigits.format(oldsalary[i]) + "\nNew Salary: $" + twoDigits.format(newsal[i]) + "\nSalary Change: $" + twoDigits.format(indsaldif[i])+"\n");
                 //**  
                                }
                sb.append("---------- \nTotal Employee Salary Increase: $" + twoDigits.format(saldiff) + "\n# of Salary Increases: " + change);
                JOptionPane.showMessageDialog(null, sb.toString());}

}

Solution

  • When you pass in change to your method, Java passes a copy of that value. The method may change the copy, but it's not reflected in the original change you declared in main.

    To maintain your change count throughout the class, have numsalchange declare a local variable initialized to 0, and it can increment it as it sees fit. Then it should return that value, and main can add that returned value to change.