Search code examples
javafor-loopjgrasp

Displaying values which needed to be added that are present in a for loop in java


The purpose of the program is to collect how much a person makes every week, add it up and display how much they make in a month. The for loop works just fine. My question is how do i add all the values of payweek and display them in the print statement outside the for loop.

import java.util.Scanner;
public class Burger
{
    static Scanner console = new Scanner (System.in);
    public static void main(String args [])
    {
        double payweek;
        int hours;
        for( int w = 1; w < 5; w++;){
            System.out.print("How many hours did you work in week" +w +"?");hours = console.nextInt();
            payweek = 0.7*5.15*hours;
            System.out.println("Your take home pay is $" + payweek);
        }
        System.out.println("Your total pay for the month is ");
    }
}

Solution

  • import java.util.Scanner; 
    public class Burger { 
            static Scanner console = new Scanner (System.in); 
            public static void main(String args []) {
    
                 double payweek;
                 int hours;
                 double monthPay = 0;
                 for( int w = 1; w < 5; w++;){
                         System.out.print("How many hours did you work in week" +w+"?");hours = console.nextInt();
                         payweek =  0.7*5.15*hours;
                         monthPay = monthPay + payweek;
                         System.out.println("Your take home pay is $" + payweek);
               }
               System.out.println("Your total pay for the month is "+monthPay);
           }
        }
    

    You just have to take variable which sums all payweek and then print it outside the loop. I think it helps.