I think from this point forward i will try and hit on the major points of the chapter and then go straight to the programming exercises at the end of the chapter. As i get a little deeper into the book I am hoping to do them in Java for review and then in Ruby. For now I am going to do them in Ruby only so I can make up some ground and mostly because the exercises are very basic and easy for anyone who already knows a specific language.
So here are the exercises in Ruby:
2.1 Write a program that reads a Celsius degree in double from the console, then converts it to Fahrenheit and displays the result.
The math is F = (9/5) * celsius + 32
Here is the code.. (very similar to our last example)
class ChapterTwoQuestionOne
puts "what is the temperature in Celsius?"
cels = gets
cels = cels.to_i #converts our string to an integer
puts 9.0/5 * cels + 32
end
problem 2.2 Write a program that reads in the radius and length of a cylinder and computes the volume using the following formula:
area = radius * radius * 3.14
volume = area * length
here is the code:
class ChapterTwoQuestionTwo
puts "what is the radius?"
radius = gets
radius = radius.to_f
puts "what is the length?"
leng = gets
leng = leng.to_f #convert to float ( because we need the decimals!)
area = radius * radius * 3.14159
puts area
volume = area * leng
puts volume
end
Since most of these are very similar i will skip ahead to problem 2.6
Problem 2.6 Write a program that reads an integer between 0 and 1000 and adds all the digits in the integer. For example if an integer is 932 the sum of the integers is 14.
A little bit more involved, the text implies that you should use the remainder operator, which is how i will do it.
here is the code:
class ChapterTwoQuestionSix
puts "enter an integer between 0 and 999"
number = gets
number = number.to_i
num1 = number%100
num1 = num1%10
num2 = number /10
num2 = num2%10
num3 = number/100
puts num1 +num2+ num3
end
Good refresher on the remainder operator.. but so far not a whole lot of challenge. I have found that Ruby is so far in the basic sense very very easy to pick up on the language elements.
Chapter 3 is ahead and contains selections, which means some boolean stuff as well as if statements and nested if statements and etc.
There is quite of bit in my textbook that uses JOptionPane for input and output, which is from the Java swing class. I haven't looked very hard yet, but i have noticed that there doesn't seem to be an obvious Ruby version of Swing.. which is probably mostly due to the nature of what Ruby is used for in programming in general as opposed to Java.
As i get some time this week hopefully i can find a solution or a way implement some i/0 version in ruby.
No comments:
Post a Comment