|
Spring Semester 2005
|
Last time we looked at two types of numbers:
- integers (such as
-5,23,10345and so forth) and- floating-point numbers (examples include:
5.7,12.0,-3.14, etc.)We will use
intto denote the first category of numbers.(Occasionally
longwill also be used and explained.)
We will use
doubleas the label for the second category.(Although
floatwill also be used from time to time).We use numbers to create expressions, which is a way of calculating other numbers.
The operators we looked at are:
-(unary minus, as in-5)+(addition for numbers, concatenation forStrings)*(multiplication)/(division)%(remainder)If the two operands in an expression are both integers the result is also an integer.
If one of the two operands in an expression is a
doublethe result will be adouble.So, some examples are:
1/2evaluates to01.0/2evaluates to0.5
Some operators have precedence over others:
- unary minus has the highest precedence (must be done first)
- multiplication and division (and remainder too) come next
- addition and subtraction have the lowest precedence
The order of the operations can be specified by parentheses.In their absence operations of the same precedence are to be performed left to right.
Here are some examples:
1 + 2 - 3evaluates to01 - 2 + 3evaluates to21 / 2 * 3evaluates to03 * 1 / 2evaluates to11.0 / 2 * 3evaluates to1.51 / 2 * 3.0evaluates to0This last one is (hopefully) clear.
Some more examples:
2 + 3 * 4evaluates to142 * 3 + 4evaluates to102 * (3 + 4)evaluates to14
Math.sqrt(...) and Math.pow(...)Instead of operators we use:
Math.sqrt(x)to calculate the square root ofxMath.pow(x, y)to raisexto the power ofyWhat can we do with these expressions outside of printing their result?
We can store the number they evaluate to, for later use.
For that we use variables, which are:
names for locations that can keep values of a certain type.The only types we know thus far are:
int(for integers) anddouble(for floating-point numbers)
Here's how you declare and initialize a variable of typeint:int n; // declaration n = 1; // initialization to 1n = 1;is an assignment statement:
Here's how you declare and initialize a variable of type
- it has two parts separated by the equal sign
- on the left is the name of the variable whose value is being changed
- on the right there's an expression that must be of compatible type with the variable
- the expression is evaluated first, then the value is assigned to the variable
int:You will notice that in the last exampledouble m; // declaration m = 1.0; // initialization to 1would have worked just as well.m = 1;
1is compatible withdoubleandmis now1.0as a matter of fact.In the previous example
would have also been correct, butn = 6 / 3;would give an error. There's no room for the decimal part inn = 6.0 / 3.0;neven if it's0(zero).A variable should not be declared more than once.
A variable can changed its value any number of times.
If types are compatible they can also be converted:The last assignment uses casting.m = 6; n = (int)2.3 // n contains 2 nowIn this case we drop the decimal part on purpose.
ConsoleReader) The rest of this lecture will introduceConsoleReader, which is a kind ofPenguin.
You only need to know how to use it./******************************************************* ConsoleReader class is used for keyboard input. Just keep the source code of this class (the file) in the same directory in which your other program (the one that needs user input) resides. In this particular case keep it in the same folder with Conversion.java that has been presented above. ********************************************************/ import java.io.*; // I/O package needed class ConsoleReader { ConsoleReader(InputStream inStream) { // constructor reader = new BufferedReader( new InputStreamReader( inStream)); } String readLine() { // instance method String inputLine = ""; try { inputLine = reader.readLine(); } catch (IOException e) { System.out.println(e); System.exit(1); } return inputLine; } int readInt() { // instance method String inputString = readLine(); int n = Integer.parseInt(inputString); return n; } double readDouble() { // instance method String inputString = readLine(); double x = Double.parseDouble(inputString); return x; } private BufferedReader reader; // instance method }
So we will discuss this program:/* A conversion program that illustrates how one can read input from the keyboard using the textbook's ConsoleReader class */ class Conversion { public static void main(String[] args) { ConsoleReader console = new ConsoleReader(System.in); // now we can read from 'console' System.out.println("Hi my name is Hal. What is your name?"); //// greet the user String name = console.readLine(); //// wait for input and collect it (a String, for the name) System.out.print("Hello, " + name + "! "); //// echo the name to the user, raising user's confidence in us System.out.println("How many dollars do you want to convert?"); //// approach the user directly, offer your services System.out.println("(Please type an integer value, no decimal part)"); //// instruct the user what limitations you have (accepting only int's) int amount = console.readInt(); //// wait for the user to provide the sum to be converted System.out.println("I see, you want to convert " + amount + " dollars in British pounds. Very well..."); //// talk to the user, be friendly, echo information frequently System.out.println("What is the conversion rate today?"); //// ask the user for the last piece of input double rate = console.readDouble(); //// wait for the conversion rate, which can have a fractional part System.out.println("Well, "+ name + " for " + amount + " dollars " + "you can get: " + rate * amount + " pounds."); //// do the calculation and report it to the user System.out.println("Thank you for using Hal! Good-bye."); //// thank the user for interest and say good-bye } }
The last thing we need to make clear is that strings of characters are different.You can't say:
If you really want something like that you'd have to convert:int n = "12"; // won't workIf the conversion fails you will find out, the program will crash.int n = Integer.parseInt("12"); // now n is set to 12
Strings are indicated by characters grouped between double quotes.You need a backslash in front of it (as in
\") to indicate a double quote inside a string.(The backslash is an escape character. It disables the normal meaning of a double quote, as a delimiter.)
The backslash in front of a normal lowercase
nindicates a newline.(You wouldn't otherwise be able to write a newline in the string, since that would break the line.)
To indicate a backslash use the backslash in front of a backslash:
\\.So
"\"\\\n"prints as a double quote followed by a backslash and a newline.Strings could be concatenated using
+.Thus
"blue" + "berry"evaluates to"blueberry".There will be a few more rules to keep in mind.
Tue Jan 18 14:56:06 EST 2005