Search code examples
javaloopswhile-loopaccounting

Calculating double diminishing depreciation using loops


So I have to come up with a code that calculates depreciation using double diminishing method.

So far I got this code:

    Scanner kbd = new Scanner (System.in);

    System.out.println("Please enter asset number: ");
    assetNum = kbd.nextInt();

    System.out.println("Please enter initial purchase price: ");
    purchPrice = kbd.nextDouble();

    System.out.println("Please enter useful life of the asset (in years): ");
    usefulLife = kbd.nextDouble();

    System.out.println("Please enter the salvage value: ");
    salvageVal = kbd.nextDouble();

    System.out.println("Please enter the number of years of depreciation: ");
    numYears = kbd.nextDouble();

    ddRate = ((1.0 / usefulLife) * 2) * 100;

    System.out.println("Asset No: " + assetNum);
    System.out.printf("Initial Purchase Price: $%,.0f%n" , purchPrice);
    System.out.printf("Useful Life: %.0f years%n" , usefulLife); 
    System.out.printf("Salvage Value: $%,.0f%n" , salvageVal);
    System.out.printf("Double Declining Rate: %.0f%%%n" , ddRate);
    System.out.printf("Number of Years: %.0f years%n" , numYears);
    System.out.println();

    System.out.println("Year          Yearly          Accumulated          Book");
    System.out.println("              Depreciation    Depreciation         Value");
    System.out.println();

    int year;
    double yearlyDepr;
    double accDepr;
    double bookVal;

    bookVal = purchPrice;
    accDepr = 0;
    year = 0;
    while (bookVal >= salvageVal){
        yearlyDepr = bookVal * (ddRate / 100);
        accDepr = accDepr + yearlyDepr;
        bookVal = bookVal - yearlyDepr;
        year++;

        System.out.printf("%d %,18.0f %,18.0f %,18.0f%n" , year, yearlyDepr, accDepr, bookVal);
    }
}

}

The output looks good until the last row with a book value of 7,776 instead of the salvage value of 10,000.

Mines like this: http://puu.sh/zyGzg/e35ccf0722.png

Should be like this: http://puu.sh/zyGBM/4b6b8fa14c.png

Please help, I'm really stuck.


Solution

  • In your while loop you need to test if the new bookVal will be less than salvageVal and if so use the salvageVal

    while (bookVal > salvageVal){   // also change
        yearlyDepr = bookVal * (ddRate / 100);
        accDepr = accDepr + yearlyDepr;
        bookVal = bookVal - yearlyDepr;
        year++;
    
        if (bookVal < salvageVal) {
            bookVal = salvageVal;
            yearlyDepr = purchPrice - salvageVal;
        }
    
        System.out.printf("%d %,18.0f %,18.0f %,18.0f%n" , year, yearlyDepr, accDepr, bookVal);
    }