mardi 19 avril 2016

How to change variable outside a loop

public static void main(String[] args) {

    Scanner keyboard = new Scanner (System.in);
    double budget, total, expenseTotal;

    System.out.print("Enter your budget for the month: "); 
    budget = keyboard.nextDouble();           
    System.out.println("Type -99 to stop calculations\n");
    byte start = 1; 

    double expense = 0;  

    while (expense != -99) {

        System.out.print("Enter expense " + start + " :"); 
        expense = keyboard.nextDouble(); 

        start++;             

        if (expense == -99) {
            System.out.println(); 
            total = (budget - expense) - 99; 
            System.out.printf("Your current total budget is: $%,.2f \n" , total); 
        }
    }   
}

Current output:

Enter your budget for the month: 1000 Type -99 to stop calculations

Enter expense 1 :100

Enter expense 2 :-99

Your current total budget is: $1,000.00

Desired output:

Your current total budget is: $900.00

Problem : expense was declared outside of the while statement and given the number 0. I figured that since expense = keyboard.nextDouble(); was in the loop that it would update the expense that was placed outside of the loop but it didn't. So any solutions? Thanks.

Aucun commentaire:

Enregistrer un commentaire