Object Oriented Basics(homework for 03)

Object Oriented Basics

                                                                                                                                ——孙琨SealSun

1、问题

 

Define a class BookInStock which represents a book with an ISBN number, isbn, and price of the book as a floating-point number, price, as attributes.

  The constructor should accept the ISBN number (a string, since in real life ISBN numbers can begin with zero and can include hyphens) as the first argument and price as second argument, and should raise ArgumentError (one of Ruby's built-in exception types) if the ISBN number is the empty string or if the price is less than or equal to zero. Include the proper getters and setters for these attributes.

  Include a method price_as_string that returns the price of the book formatted with a leading dollar sign and two decimal places, that is, a price of 20 should format as "$20.00" and a price of 33.8 should format as "$33.80".


2、解决代码


<span style="font-size:14px;">#-------------------------------
#-----程序名称:homework for 03
#-----编译环境:ruby 2.2.3
#-----作    者:孙琨SealSun
#-----编写地点:UCAS  
#-----编写时间:2015年10月05日  
#--------------------------------

class BookInStock
# YOUR CODE HERE
  def initialize(isbn,price) #构造函数
    @isbn=isbn
    @price=price
    if(@isbn===""||@price<=0) #异常处理
      raise ArgumentError
    end
  end

 #set,get方法
  def set_isbn(isbn)
    @isbn=isbn
    if(@isbn==="")
      raise ArgumentError
    end
  end

  def set_price(price)
    @price=price
    if(@price<=0)
      raise ArgumentError
    end
  end

  def get_isbn
    puts @isbn
  end

  def get_price
    puts @price
  end

  def price_as_string #price处理
    puts "$"+format("%.2f", @price)
  end
end
  begin
    # a = BookInStock.new(123,2) #for testing
    # #a.set_price(15.2)
    # a.get_price
    # a.price_as_string  
    rescue ArgumentError=>e
      puts "发生错误,错误为ISBN为空,或者价格<=0"
  end</span>




  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值