Chapter 2 starts at looking how some simple programs are constructed, as well as assigning variables and getting input from the console.
Primarily it looks at the assignment of variables and the Java Scanner class.
The Scanner class in Java is used to get input and used to display output. Obviously the default input is the keyboard and the default output is the monitor.
Console input is not directly supported in Java , but you can simply import the Scanner class to create a Scanner Object and then read the input calling System.in.
here is an example:
Scanner input = new Scanner (System.in);
(input being the name of the new Scanner object that you created with the new operator.
I will copy some sample code from my textbook, describe what the code is doing, and then try and recreate the program in Ruby.
............................................................................................................................................
import java.util.Scanner;
// imports a class from java to handle the scanner input/output
public class RadiusComputation{
public static void main(String args[ ]){
// above is the class and of course our main method
Scanner input = new Scanner (System.in);
// this makes a new scanner and names it input, allows you to input a number
System.out.print("enter a number for the radius");
// this prints to the console the request for the user to enter a radius
double radius = input.nextDouble( );
// this takes the number from the console and assigns it to the variable "radius"
double area = radius * radius * 3.14159;
// this does the math involved in calculating a circle's area, and then it assigns it to
// the variable "area"
System.out.println("the radius of the circle is " + radius + "and the area is " + area);
// this is our ouput which takes the statement, adds in the variables and outputs to the screen
}
}
Now lets see if we can do this in Ruby!
class ChapterTwo
puts "what is the radius of the circle?"
radius = gets
# gets is our "scanner in"
radius = radius.to_i
# radius.to_i is how we convert the string to an integer in Ruby
puts radius * radius * 3.14159
#this is how we output the answer
end
puts "what is the radius of the circle?"
radius = gets
# gets is our "scanner in"
radius = radius.to_i
# radius.to_i is how we convert the string to an integer in Ruby
puts radius * radius * 3.14159
#this is how we output the answer
end
So in the end pretty simple! I learned a way in Ruby to get input and a way to convert a string into a number. Very nice.
Moving forward in this chapter we will be looking at getting input of multiple numbers, identifiers, order of operations, variables, numeric data types and more!
No comments:
Post a Comment