Object Oriented Basics(homework for 03)

来源:互联网 发布:乌克兰男女比例知乎 编辑:程序博客网 时间:2024/06/05 17:06

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)  endend  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
原创粉丝点击