More on Operators and Assignments
PLUS: Reading Input from the Keyboard!!





If you can't write it down in English, you can't code it.
                     -- Peter Halpern



If you lie to the computer, it will get you.
                    -- Peter Farrar



One person's constant is another person's variable.
                   -- Alan Perlis








But First... More on Operators





Operator precedence - highest to lowest

Note
: Recall that + is an operator that adds 2 numbers, but it also is the string concatenation operator when one or both operands are Strings.




Examples:
int result = 2 * ((16 - 4) / 2);  // result is set to 12
String s = 4 + "6" + 2;  // s is set to "462"
result = 13 % 2 - 1;  // result is set to 0
result = 13 % 2 * 4;  // result is set to 4





Increment and Decrement Operators



Example:
int count = 1;
count ++;
System.out.println(count);
-- count;
System.out.println(count);

Question: What is the output?


Example: Try out the following code:
int count = 1;
int n = 2 + count++;

And then try:
int count = 1;
int n = 2 + ++count;






Assignment Operators



Ex:
count += 5;
       is equivalent to
count = count + 5;

Ex:
int result = 2;
result *= 4;   // result is 8


Ex:
int count1 = 3;
int count2 = 6;
int product *= count1 + count2;   // what value is stored in product?
       is equivalent to
int product = product * (count1 + count2);


Ex:
String s = "hello";
s += " world";             // s is "hello world"
        is equivalent to
s = s + " world";






Input from the Keyboard



                 Scanner scan = new Scanner(System.in);






Example:
Scanner scan = new Scanner(System.in);

// Prompt the user to enter an integer
System.out.print("Please enter an integer: ");

// Read and print the integer
int value = scan.nextInt();
System.out.println(value);




Example: Write a program that asks the user to enter a line of text, and then prints the first word in the line to the screen.

Example: Write a program that asks the user to enter a line of text, and then prints the line to the screen.

Example: Write a program that asks the user to enter 3 (integer) exam scores, and then prints the average.