集册 Java实例教程 具有双重实例变量余额以及执行验证的构造函数和存款方法的帐户类。

具有双重实例变量余额以及执行验证的构造函数和存款方法的帐户类。

欢马劈雪     最近更新时间:2020-01-02 10:19:05

587
使用Account对象输入和输出浮点数。

import java.util.Scanner;


public class Main

{//N o  w  J a v a . c o m - 时  代  Java

   public static void main(String[] args) 

   {

      Account account1 = new Account("James Bond", 50.00);

      Account account2 = new Account("Michael Bates", -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()); 


      // create a Scanner to obtain input from the command window

      Scanner input = new Scanner(System.in);

      /*
      n o w j a   v  a . c o m - 时  代  Java 提供
      */

      System.out.print("Enter deposit amount for account1: "); // prompt

      double depositAmount = input.nextDouble(); // obtain user input

      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()); 


      System.out.print("Enter deposit amount for account2: "); // prompt

      depositAmount = input.nextDouble(); // 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()); 

   } 

}

class Account

{   

   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


      // validate that the balance is greater than 0.0; if it's not,

      // instance variable balance keeps its default initial value of 0.0

      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) 
展开阅读全文