Java class Constructors parameter validation

Description

Java class Constructors parameter validation


// Inputting and outputting floating-point numbers with Account objects.
import java.util.Scanner;
class Account/*from ww w.j a va  2s  .  com*/
{   
   private String name; // instance variable 
   private double balance; // instance variable 

   // Account constructor that receives two parameters  
   public Account(String name, double balance) 
   {
      this.name = name; // assign name to instance variable name
      if (balance > 0.0) // if the balance is valid
         this.balance = balance; // assign it to instance variable balance
   }

   // method that deposits (adds) only a valid amount to the balance
   public void deposit(double depositAmount) 
   {      
      if (depositAmount > 0.0) // if the depositAmount is valid
         balance = balance + depositAmount; // add it to the balance 
   }

   // method returns the account balance
   public double getBalance()
   {
      return balance; 
   } 

   // method that sets the name
   public void setName(String name)
   {
      this.name = name; 
   } 

   // method that returns the name
   public String getName()
   {
      return name; 
   } 
} 
public class Main
{
   public static void main(String[] args) 
   {
      Account account1 = new Account("CSS", 50.00);
      Account account2 = new Account("Java", -7.53); 

      // display initial balance of each object
      System.out.printf("%s balance: $%.2f%n",
         account1.getName(), account1.getBalance()); 
      System.out.printf("%s balance: $%.2f%n%n",
         account2.getName(), account2.getBalance()); 


      double depositAmount = -2; 
      System.out.printf("%nadding %.2f to account1 balance%n%n", depositAmount);
      account1.deposit(depositAmount); // add to account1's balance

      // display balances
      System.out.printf("%s balance: $%.2f%n",account1.getName(), account1.getBalance()); 
      System.out.printf("%s balance: $%.2f%n%n",account2.getName(), account2.getBalance()); 

      depositAmount = -100; // obtain user input
      System.out.printf("%nadding %.2f to account2 balance%n%n", 
         depositAmount);
      account2.deposit(depositAmount); // add to account2 balance

      // display balances
      System.out.printf("%s balance: $%.2f%n", 
         account1.getName(), account1.getBalance()); 
      System.out.printf("%s balance: $%.2f%n%n",
         account2.getName(), account2.getBalance()); 
   } // end main
}



PreviousNext

Related