In: Computer Science
How to create a program Budget
Enter the amount budgeted for the month: 400
Enter the expense (-1 to quite):100
Enter the expense (-1 to quite):-1
$400 budgeted.
1 expenses totaling $100.
$300 under budget.
Need to use sentinel value of -1, while loop
Program in java:
//importing class for user input
import java.util.Scanner;
//class declaration
public class Budget
{
   //main method
   public static void main(String args[])
   {
       //variables
       int
budget,amt,totamt=0,count=0;
       //creating object for taking user
input
       Scanner inp=new
Scanner(System.in);
       //asking for user input
       System.out.print("Enter the amount
budgeted for the month: ");
       //storing the value provided by
user
       budget=inp.nextInt();
       //using do while loop to write the
logic
       do
       {
           //asking for the
expenses from user
          
System.out.print("Enter the expense (-1 to quite): ");
           //storing user
input
          
amt=inp.nextInt();
           //if the passed
value is not sentinel
          
if(amt!=-1)
           {
          
    //increment the count
          
    count++;
          
    //reassign the total
          
    totamt=totamt+amt;
           }
       //checking for sentinel case to
exit the loop
       }while(amt!=-1);
       //printing the results
       System.out.println("$"+budget+"
budgeted.");
       System.out.println(count+" expenses
totaling $"+totamt);
      
System.out.println("$"+(budget-totamt)+" under budget.");
   }
}
Output:
