Download presentation
1
CISC6795, Xiaolan Zhang, Fordham University
Java RevIEW: II CISC6795, Xiaolan Zhang, Fordham University
2
Outline Read input from users Variable, primitive types, expressions
Use packages Variable, primitive types, expressions Pseudocode, control structure Sequence Selection statement Repetition statement
3
Outline import declaration imports class Scanner from package java.util. Addition. java (1 of 2) import declaration Scanner nextInt Declare and initialize variable input, which is a Scanner. Read an integer from the user and assign it to number1.
4
Outline Read an integer from the user and assign it to number2. Additio n.java (2 of 2) 4. Addition 5. printf Display the sum using formatted output. Two integers entered by the user.
5
Import Declaration import java.util.Scanner; // program uses class Scanner Tell compiler to load class Scanner from java.util package Package: a named collection of related classes Must appear before first class declaration Alternatively, import java.util package import java.util.*; Forgetting to “import” a class/package => compilation error such as “cannot resolve symbol.” By default, package java.lang is imported in every Java program only package in Java API that does not require an import declaration.
6
Variable declaration statement
// create Scanner to obtain input from command window Scanner input = new Scanner( System.in ); Same as Scanner input; input = new Scanner (System.in); Variables declaration VariableType VariableName; A variable is a location in memory that stores a value, must be declared before used Variable name: any valid identifier (recall the rule?) Initialize variable in its declaration Equal sign stands for assignment operator The parameter System.in refers to standard input object (often links to keyboard): input variable will be used to read inputs from keyboard
7
Primitive types Declare variable number1, number2 and sum of type int
int number1; // first number to add int number2; // second number to add int sum; // second number to add Declare variable number1, number2 and sum of type int Primitive types in Java: int, float, double, char, byte, boolean int holds integer values (whole numbers): i.e., 0, -4, 97 Types float and double hold decimal numbers Type char holds a single character: i.e., x, $, \n, 7 Can declare multiple variables of the same type in one declaration Use comma-separated list int number1, // first number to add number2, // second number to add sum; // second number to add
8
Primitive Types Java requires all variables to have a type.
Primitive types in Java are portable across all platforms. Same size across all platforms, int is always 23 bits, … Local variables of types char, byte, short, int, long, float and double, i.e., those declared in a method Are not initialized by default Using a variable without initializing it => compilation error
9
Good Programming Practice
Declare each variable on a separate line allows a descriptive comment to be easily inserted next to each declaration. Choose meaningful variable names self-documenting program Convention for variable-name identifiers begin with a lowercase letter, and every subsequent word in the name begins with a capital letter e.g., firstNumber, studentRecord, …
10
Reading from keyboard Result of call to nextInt given to number1 using assignment operator = Assignment statement = binary operator - takes two operands Expression on right evaluated and assigned to variable on left Place spaces on both side of binary operator for more readable code Read as: number1 gets the value of input.nextInt() How to read double, char, …? Online Java API document for the version of Java you use Examples used through the class are for Java SE 6 number1 = input.nextInt(); // read first number from user
11
Adding Integers Assignment statement
Calculates sum of number1 and number2 (right hand side) Uses assignment operator = to assign result to variable sum Read as: sum gets the value of number1 + number2 number1 and number2 are operands sum = number1 + number2; // add numbers
12
Displaying result Use System.out.printf to display results
System.out.printf( "Sum is %d\n: " , sum ); // display sum Use System.out.printf to display results Format specifier %d Placeholder for an int value Calculations can also be performed inside printf Parentheses around the expression number1 + number2 are not required System.out.printf( "Sum is %d\n: " , ( number1 + number2 ) );
13
Variables stored in memory
Variable has a name, a type, a size and a value Variables are stored in main memory Size of memory depends on the type Name corresponds to location in memory Mapping performed by compiler Assignment statement: place new value into variable, replaces (and destroys) previous value Reading variables from memory does not change them
14
Arithmetic Expression
Arithmetic calculations * for multiplication / for division % for remainder +, - Integer division truncates remainder 12 / 5 evaluates to 2 Remainder operator % returns the remainder 7 % 5 evaluates to 2
15
Arithmetic operators Exercise: write an expression to convert temperature from Farenheith degree to Celsus degree: Hint: Tf = (9/5)*Tc+32; Tc = temperature in degrees Celsius Tf = temperature in degrees Fahrenheit
16
Operator Precedence Some arithmetic operators act before others (i.e., multiplication before addition) Use parenthesis when needed
17
Casting To calculate average value of count # of integers:
average = (double) total / count; Unary cast operator (double) creates a temporary floating- point copy of its operand. The value stored in its operand is unchanged. To perform a floating-point calculation, temporarily treat these values as floating-point numbers for use in the calculation. Cast operator performs explicit conversion (or type cast). Operands’ type in an arithmetic expressions should be identical. In an expression containing values of types int and double, int values are promoted to double values for use in the expression. count is casted to double too, this is called Promotion (or implicit conversion).
18
Cast operators Cast operators are available for any type.
Sometimes this lead to loss of information int dollarAmount; double changes = amountReceived – amountDue; dollarAmount = (int) changes; Cast operators associate from right to left same precedence as other unary operators, such as unary + and unary – double a=10.35; double b=(double)(int)a;
19
Good Programming Practice
Refer to operator precedence chart when writing expressions containing many operators. When uncertain, use parentheses to force the order Some operators, such as assignment, =, associate from right to left rather than from left to right.
20
Exercise Exercise: write an expression to convert temperature from Farenheith degree to Celsus degree: Tf = (9/5)*Tc+32; Tc : temperature in degrees Celsius Tf : temperature in degrees Fahrenheit In lab1 assignment, you will implement a Cashier program. One task is to direct the cashier to give changes to the customer: If the change is $12.34, the program displays “Give 12 dollars, 1 quarter, 5 nickels and 4 pennies.”
21
Problem Solving Approach
Don’t start coding right away Unless it’s a trivia problem Before writing a program to solve a problem Have a thorough understanding of the problem Carefully plan your program to solving the problem, i.e., algorithm Understand available building blocks Employ proven program-construction techniques Top-down technique
22
Algorithms An algorithm is a procedure for solving a problem in terms of the actions to execute and the order in which these actions execute One Rise-and-shine algorithm: (1) Get out of bed; (2) take off pajamas; (3) take a shower; (4) get dressed; (5) eat breakfast; (6) carpool to work. Easier? Now how to take a shower …
23
Pseudocode Pseudocode: an informal language for describing algorithms without having to worry about language details Helps you “think out” a program before attempting to code Carefully prepared pseudocode can easily be converted to a corresponding program. Like program language, also have control structure for constructing loops, selection
24
Control Structures Sequential execution: Statements in a program execute one after the other in the order in which they are written. Transfer of control: Statements in a program that which enable change of next statement to execute, i.e., not necessarily next one in sequence. All programs can be written in terms of only three control structures—the sequence structure, the selection structure and the repetition structure.
25
Selection statements if statement: Single-selection statement
Performs an action, if a condition is true; skips it, if false. Selects or ignores a single action (or group of actions). if…else statement: Double-selection statement Performs an action if a condition is true and performs a different action if the condition is false. Selects between two different actions (or groups of actions). switch statement: Multiple-selection statement Performs one of several actions, based on the value of an expression. Selects among many different actions (or groups of actions).
26
Repetition/Looping Statements
Perform statements repeatedly while a loop- continuation condition remains true. while and for statements perform the action(s) in their bodies zero or more times if the loop-continuation condition is initially false, the body will not execute. The do…while statement performs the action(s) in its body one or more times. if, else, switch, while, do and for are keywords.
27
Condition Condition: expression that is either true or false
Selection and repetition statements involve conditions : if (condition) body while (condition) Condition: expression that is either true or false can be formed using equality or relational operators if ( number1 >= number2 ) System.out.printf( "%d >= %d\n", number1, number2 ); If the condition is true, then the body of the if statement executed while the condition is true, repeat to execute the body of the loop
28
Equality and relational operators
No spaces between symbols in operators ==, !=, >= and <=. Reversing operators !=, >= and <=, as in =!, => and =<, is a syntax error.
29
Common Programming Error
Confusing equality operator, ==, with assignment operator, =, leads to logic error or syntax error. == read as “is equal to” = read as “gets”, or “gets the value of.”
30
if Single-Selection Statement
Pseudocode If student’s grade is greater than or equal to 60 Print “Passed” If the condition is false, the Print statement is ignored, and the next pseudocode statement in order is performed. Indent the body of the statement Emphasizes the inherent structure of structured programs The preceding pseudocode in Java: if ( studentGrade >= 60 ) System.out.println( "Passed" );
31
if…else Double-Selection Statement
if…else double-selection statement: specify an action to perform when the condition is true and a different action when the condition is false. Pseudocode if student’s grade is greater than or equal to 60 Print “Passed” else Print “Failed” Converting the pseudocode statement into Java: if ( grade >= 60 ) System.out.println( "Passed" ); else System.out.println( "Failed" ); Note that the body of the else is also indented.
32
Conditional Operator Conditional operator (?:)—shorthand for if…else.
System.out.println( studentGrade >= 60 ? "Passed" : "Failed" ); Ternary operator (takes three operands) studentGrade >= 60 ? "Passed" : "Failed“ Evaluates to the string "Passed" if the boolean expression studentGrade >= 60 is true and to the string "Failed" if it is false. the value if the boolean expression evaluates to false. a boolean expression evaluates to a boolean value (true or false) the value if the boolean expression is true
33
Nested If…else statement
Nested if…else statements : place an if…else statement as the body for another if … else statement Useful for testing multiple cases Pseudocode: If student’s grade is greater than or equal to 90 Print “A” else If student’s grade is greater than or equal to Print “B” else If student’s grade is greater than or equal to Print “C” else If student’s grade is greater than or equal to Print “D” else Print “F”
34
Nested if…else Statement
In Java: if ( studentGrade >= 90 ) System.out.println( "A" ); else if ( studentGrade >= 80 ) System.out.println( "B" ); else if ( studentGrade >= 70 ) System.out.println( "C" ); else if ( studentGrade >= 60 ) System.out.println( "D" ); else System.out.println( "F" );
35
Nested if … else statement
Alternative formatting if ( studentGrade >= 90 ) System.out.println( "A" ); else if ( studentGrade >= 80 ) System.out.println( "B" ); else if ( studentGrade >= 70 ) System.out.println( "C" ); else if ( studentGrade >= 60 ) System.out.println( "D" ); else System.out.println( "F" ); The two formats are identical except for the spacing and indentation, which the compiler ignores.
36
if…else Double-Selection Statement
Dangling-else problem: Which if does the else associated with ? if ( x > 5 ) if ( y > 5 ) System.out.println( "x and y are > 5" ); else System.out.println( "x is <= 5" ); Java always associates an else with the immediately preceding if, unless told to do otherwise by braces ({ and }). The compiler actually interprets the statement as if ( x > 5 ) if ( y > 5 ) System.out.println( "x and y are > 5" ); else System.out.println( "x is <= 5" ); This is a logic error, as the program is not doing what the programmer intend it to do.
37
if…else Double-Selection Statement
To force the nested if…else statement to execute as it was originally intended: if ( x > 5 ) { if ( y > 5 ) System.out.println( "x and y are > 5" ); } else System.out.println( "x is <= 5" ); Braces indicate that the second if is in the body of the first and that the else is associated with the first if.
38
Block Statement To include several statements in the body of an if, or the body of an else, enclose the statements in braces. Statements contained in a pair of braces form a block. A block can be placed anywhere that a single statement can be placed. if ( grade >= 60 ) System.out.println("Passed"); else { System.out.println("Failed"); System.out.println("You must take this course again."); }
39
Empty Statement Note that there is no ; after the condition
Above code has no syntax error Compiler interpret ; as empty statement If (x>0); System.out.println ((″x is not greater than 0″); Recall a block statement can be placed anywhere a single statement can be placed, so does an empty statement. Another example of logic error ! if (x>0); System.out.println (″x is not greater than 0″);
40
Exercise Review logic operators: &&, ||, ! , i.e., and, or, not operators. Write a piece of code that test whether a given year is prime year or not Write a piece of code that test whether a given date (specified by year, month and day) is a valid date or not
41
while Repetition Statement
Repetition statement—repeats an action while a condition remains true. Pseudocode While there are more items on my shopping list Purchase next item and cross it off my list Repetition statement’s body may be a single statement or a block. Eventually, the condition will become false. At this point, the repetition terminates, and the first statement after the repetition statement executes.
42
while Repetition Statement (Cont.)
Example: find smallest power of 3 that is larger than 100. int product = 3; while ( product <= 100 ) product = 3 * product; System.out.printf (“smallest power of 3 greater than 100 is %d\n”, product); Each iteration multiplies product by 3, so product takes on the values 9, 27, 81 and 243 successively. When variable product becomes 243, the while-statement condition—product <= 100—becomes false. Repetition terminates. The final value of product is 243. Program execution continues with the next statement after the while statement.
43
Formulating Algorithms: Counter-Controlled Repetition
A class of ten students took a quiz. The grades (integers in the range 0 to 100) for this quiz are available to you. Determine the class average on the quiz. The class average is equal to the sum of the grades divided by the number of students. The algorithm: input each grade, keep track of the total of all grades input, perform the averaging calculation and print the result. Use counter-controlled repetition to input the grades one at a time. A variable called a counter (or control variable) controls the number of times a set of statements will execute. Counter-controlled repetition is often called definite repetition, because the number of repetitions is known before the loop begins executing.
44
total: a variable used to accumulate the sum of several values.
A counter is a variable used to count. Variables used to store totals are normally initialized to zero before being used in a program.
47
Review: How to convert the while loop into for loop ?
48
Formulating Algorithms: Sentinel-Controlled Repetition
Develop a class-averaging program that processes grades for an arbitrary number of students E.g., “Use -1 to end” Use a special value, sentinel value, to indicate “end of data entry.” A sentinel value must be an unacceptable input value. Indefinite repetition: the number of repetitions is not known beforehand. Exercise: write a pesudocode for above problem
51
Reminder the user about
the sentinel
52
We use while loop here… Can we rewrite the code use do loop ?
Which loop is better ?
53
Some shorthand Operators
Increment operator, ++, decrement operator, -- Compound assignment operators: +=, -=, *=, …
54
Summary We review basic constructs in Java in this class
Read from standard input, write to standard output Focus now on a text-based program run from terminal GUI programming will be introduced later Variables, primitive data type, arithmetic expression Assignment operator, arithmetic operators Cast: converting a variable to another data type Control structures: sequence, selection and repetition
55
Summary (cont’d) Condition: an expression that has a boolean value
Used in selection, loop Construct a condition: relational/comparison operators, boolean operators (&&, ||, !) Selection statement: If …statement, if … else statement Repetition statement while, do, for loop Should know how to convert between them …
56
Summary (cont’d) Algorithm, Pseudocode
Construct of a loop for solving problems Initialization Body Condition Whenever writing a loop, be sure to verify that it works Are variables initialized before the loop? Will the loop terminate properly?
Similar presentations
© 2025 SlidePlayer.com Inc.
All rights reserved.