sophiasapiens.chez.comsophiasapiens.chez.com/informatique/Java-Programming…  · Web viewComputer...

36
Computer Science Notes Chapter 2: Elementary Programming These notes are meant to accompany Introduction to Java Programming: Brief Version, eighth edition by Y. Daniel Lang. Programming Skills in a Nutshell: At the end of this chapter you should have the following programming skills: 1. Declare numeric variables to store numbers and perform calculations with those numeric variables. 2. Declare string and character variables to store text. 3. To get information from the user of a program. 4. To program with proper style. 5. To understand the fundamental flow of any program: a. Tell the user what the program does. b. Get any needed information, either from the user or from another input source. c. Perform any needed calculations. d. Report results as output to the monitor or other output source. 6. To understand how to translate a programming problem into code: a. Decide what the program is supposed to do (unless someone tells you first). b. Decide what information you’ll need, where you’ll get it, and where you’ll store it. c. Write out how you would do the task yourself. d. Translate that task into code using the programming techniques you have at your disposal. 7. Here is a template using the key programming skills you should have at this point:

Transcript of sophiasapiens.chez.comsophiasapiens.chez.com/informatique/Java-Programming…  · Web viewComputer...

Page 1: sophiasapiens.chez.comsophiasapiens.chez.com/informatique/Java-Programming…  · Web viewComputer Science Notes. Chapter 2: Elementary Programming. These notes are meant to accompany

Computer Science Notes

Chapter 2: Elementary ProgrammingThese notes are meant to accompany Introduction to Java Programming: Brief Version, eighth edition by Y. Daniel Lang.

Programming Skills in a Nutshell:At the end of this chapter you should have the following programming skills:

1. Declare numeric variables to store numbers and perform calculations with those numeric variables.2. Declare string and character variables to store text.3. To get information from the user of a program.4. To program with proper style.5. To understand the fundamental flow of any program:

a. Tell the user what the program does.b. Get any needed information, either from the user or from another input source.c. Perform any needed calculations.d. Report results as output to the monitor or other output source.

6. To understand how to translate a programming problem into code:a. Decide what the program is supposed to do (unless someone tells you first).b. Decide what information you’ll need, where you’ll get it, and where you’ll store it.c. Write out how you would do the task yourself.d. Translate that task into code using the programming techniques you have at your disposal.

7. Here is a template using the key programming skills you should have at this point:

Page 2: sophiasapiens.chez.comsophiasapiens.chez.com/informatique/Java-Programming…  · Web viewComputer Science Notes. Chapter 2: Elementary Programming. These notes are meant to accompany

import java.util.Scanner;// The import statement tells the compiler where to find additional classes to be used.// In this case, the Scanner class will be used.// Scanner reads in and stores keystrokes from the keyboard.

/**The Chap02Basics class implements an application that * illustrates the basics of computer programming: * retrieving user input, performing calculations, * and generating output in a console. * Specifically, this program computes the area, hypotenuse, and perimeter * of a right triangle, given the lengths of the two legs. * This is meant as an example of the material in Chapter 2 of the text * _Introduction to Java Programming: Brief Version_, 8th ed. by Y. D. Liang * @author Kevin Mirus */

public class Chap02Basics{

/** Calculates the area, hypotenuse, and perimeter of a right triangle, * given the lengths of the two legs. * @param args is not used. */public static void main(String[] args){

//Tell the user what the program doesSystem.out.println("This program will calculate the hypotenuse, " +

"perimeter, and area of a right triangle given the lengths " +"of its legs.");

// ********************************************************************// Here is the portion of the code that reads data into memory.// ********************************************************************//Declare variables for the data to be read in://i.e., the lengths of the two legsdouble legA, legB;

//Declare a String object to store the uer's name,//and initalize that String to store the default name ClydeString userName = "Clyde";

//Create a Scanner object for reading in the user's inputScanner keyboard = new Scanner(System.in);

//Prompt the user for his/her name, and store in userNameSystem.out.println("Please enter your name: ");userName = keyboard.next();

//Prompt the user for the lengths of the legs,//and store those two pieces of information in legA and legB.System.out.println("Please enter the length of the "

+ "first leg of the right triangle:");legA = keyboard.nextDouble();

System.out.println("Please enter the length of the "+ "second leg of the right triangle:");

legB = keyboard.nextDouble();

// ********************************************************************// Here is the portion of the code that// performs calculations on the data in memory.// ********************************************************************//Declare variables for the quantities to be calculated.double hypotenuse, perimeter , area;

Page 3: sophiasapiens.chez.comsophiasapiens.chez.com/informatique/Java-Programming…  · Web viewComputer Science Notes. Chapter 2: Elementary Programming. These notes are meant to accompany

//Calculate the hypotenuse using the Pythagorean Theorem:// a^2 + b^2 = c^2// c = sqrt(a^2 + b^2)hypotenuse = Math.sqrt(legA*legA + legB*legB);

//Calculate the perimeter by adding up the lengths of the three sides.perimeter = legA + legB + hypotenuse;

//Calculate the area using the formula area = (1/2)(base)(height).area = 0.5 * legA * legB;

// ********************************************************************// Here is the portion of the code that displays// memory values for output.// ********************************************************************

//Report the results for hypotenuse.System.out.println();System.out.println("Okay, " + userName + ", the hypotenuse of your "

+ "right triangle is: " + hypotenuse);

//Report the results for perimeter.System.out.println("The perimeter of your "

+ "right triangle is: " + perimeter);

//Report the results for areaSystem.out.println("The area of your "

+ "right triangle is: " + area);

//Tell the user that the program is done.System.out.println("\nI hope you enjoyed your results.");

}//end of method main(String[])}//end of class Chap02Basics

This program will calculate the hypotenuse, perimeter, and area of a right triangle given the lengths of its legs.Please enter your name:KevinPlease enter the length of the first leg of the right triangle:2.8Please enter the length of the second leg of the right triangle:5.75

Okay, Kevin, the hypotenuse of your right triangle is: 6.3955062348495915The perimeter of your right triangle is: 14.945506234849592The area of your right triangle is: 8.049999999999999

I hope you enjoyed your results.

Page 4: sophiasapiens.chez.comsophiasapiens.chez.com/informatique/Java-Programming…  · Web viewComputer Science Notes. Chapter 2: Elementary Programming. These notes are meant to accompany

Book’s Statement of Skills: 1. To write Java programs to perform simple calculations (2.2)2. To obtain input from the console using the Scanner class. (2.3)3. To use identifiers to name variables, constants, methods, and classes (2.4)4. To use variables to store data (2.5 – 2.6)5. To program with assignment statements and assignment operators (2.6)6. To use constants to store permanent data (2.7) 7. To declare Java primitive types: byte, short, int, long, float, double, and char. (2.8.1)8. To use Java operators to write numeric expressions. (2.8.2 – 2.8.3)9. To display the current time. (2.9)10. To use shorthand operators. (2.10)11. To cast the value of one type to another type (2.11)12. To compute loan payments (2.12)13. To represent characters using the char type. (2.13)14. To compute memory changes (2.14)15. To represent a string using the String type. (2.15)16. To become familiar with Java documentation, programming style, and naming conventions. (2.16)17. To distinguish syntax errors, runtime errors, and logic and debug errors. (2.17)18. (GUI) To obtain input using JOptionPane input dialog boxes. (2.18)

Page 5: sophiasapiens.chez.comsophiasapiens.chez.com/informatique/Java-Programming…  · Web viewComputer Science Notes. Chapter 2: Elementary Programming. These notes are meant to accompany

Section 2.1: IntroductionThis chapter will teach you how to use primitive data types, perform input and output, and execute simple calculations.

Section 2.2: Writing Simple ProgramsWhen you write a program:

1. Decide what information you’ll need and how you’ll store it (i.e., the data structures), and where you’ll get the data (from disk or the user via keyboard or GUI input dialog box)

a. Data structures introduced in this chapter: VARIABLESi. Primitive data types

1. Integers (int, long)2. Floating-point numbers (float, double)3. Characters (char)4. Boolean data types (for true/false) (boolean)

ii. Strings – for arrays of characters (i.e., words and sentences) (String)

2. Write out how you would perform the computation yourself; i.e., outline your algorithm. An algorithm is a statement of how to solve a problem in terms of the steps to execute, and the order of those steps.

3. Decide what kind of information you want your program to show when it is done computing and the format of that information.

4. Translate that task into code using the programming techniques you have at your disposal.

Page 6: sophiasapiens.chez.comsophiasapiens.chez.com/informatique/Java-Programming…  · Web viewComputer Science Notes. Chapter 2: Elementary Programming. These notes are meant to accompany

Practice: Go through the steps above to decide how to write a program to compute the area of a rectangle, then implement (i.e., write) the program.

Plan for writing a program to compute the area of a rectangle:1. Information needed and how to store it

Length – store in a double-precision variableWidth - store in a double-precision variable

2. Algorithm:Area = length x width

3. Information to show and its format:“Echo” length & width…Ouput the area

4. Translate that task into code using the programming techniques you have at your disposal.

Program to compute the area of a rectangle:import java.util.Scanner;

/** * The RectangleArea class implements an application that * computes the area of a rectangle. * @author Kevin Mirus * */public class RectangleArea{

/** * Computes area given a length and a width. * @param args is not used */public static void main(String[] args){

//Tell the user what the program doesSystem.out.println("This program will calculate the area of a rectangle given

the lengths " +"of its sides.");

// ********************************************************************// Here is the portion of the code that reads data into memory.// ********************************************************************//Declare variables for the data to be read in://i.e., the sides of the rectangledouble length, width;

//Create a Scanner object for reading in the user's inputScanner keyboard = new Scanner(System.in);

//Prompt the user for the sides of the rectangle.System.out.println("Please enter the length of the "

+ "first side of the rectangle:");length = keyboard.nextDouble();

System.out.println("Please enter the length of the "

Page 7: sophiasapiens.chez.comsophiasapiens.chez.com/informatique/Java-Programming…  · Web viewComputer Science Notes. Chapter 2: Elementary Programming. These notes are meant to accompany

+ "second side of the rectangle:");width = keyboard.nextDouble();

// ********************************************************************// Here is the portion of the code that// performs calculations on the data in memory.// ********************************************************************//Declare variables for the quantities to be calculated.double area;

//Calculate the area of the rectangle:area = length * width;

// ********************************************************************// Here is the portion of the code that displays// memory values for output.// ********************************************************************//Echo the side dimensions.System.out.println();System.out.println("Length = " + length);System.out.println("Width = " + width);

//Print the areaSystem.out.println("Area = " + area);

}

}

Page 8: sophiasapiens.chez.comsophiasapiens.chez.com/informatique/Java-Programming…  · Web viewComputer Science Notes. Chapter 2: Elementary Programming. These notes are meant to accompany

VARIABLE: a piece of memory with a name used for storing data and computational results. Choose descriptive names for variables.

o Example: good variable names to represent the legs of a right triangle would be legA and legB as opposed to a and b.

Variables must be declared in Java before they are used so that the JVM can set aside the appropriate amount of memory. Example:

//Declare variables for the data to be stored: i.e., the lengths of the two legsdouble legA, legB;

//Declare variables for the quantities to be calculated.double hypotenuse, perimeter , area;

The equals sign ( = ) is used to assign a value to a variable. Example://Calculate the area using the formula area = (1/2)(base)(height).area = 0.5 * legA * legB;

The plus sign ( + ) is used to perform numerical addition and to concatenate strings with other strings or numerical values. If a string is too long, then you should break it up over two lines using concatenation. Examples:

//Calculate the perimeter by adding up the lengths of the three sides.perimeter = legA + legB + hypotenuse;

System.out.println("Please enter the length of the "+ "first leg of the right triangle:");

System.out.println("Okay, " + userName + ", the hypotenuse of your "+ "right triangle is: " + hypotenuse);

See www.cs.armstrong.edu/liang/intro8e/book/ComputeArea.java

Page 9: sophiasapiens.chez.comsophiasapiens.chez.com/informatique/Java-Programming…  · Web viewComputer Science Notes. Chapter 2: Elementary Programming. These notes are meant to accompany

Section 2.3: Reading Input from the Console Java uses System.out (i.e., a data field named out in the System class) to refer to the "standard"

output stream or device, which is a console displayed on the monitor. To perform console output, we saw that we can use the println method with System.out

(officially, println is a method of the PrintStream class, and out is an object of type PrintStream).

Java uses System.in (i.e., a data field named in of the System class) to refer to the "standard" input stream or device, which is the keyboard.

To get access to the data flowing into the computer from the keyboard, we can use the Scanner class, which has several methods for reading different types of input from the keyboard.

To use the Scanner class to read input you need to do three things:1. Have the following statement as the very beginning of your source code:

import java.util.Scanner;2. Create a “variable” to store the information from the Scanner. Use the following line of source code:

Scanner keyboard = new Scanner(System.in);(You can change the variable name keyboard to whatever you want, but that is the only thing you can

change in the line above.)3. Store information from the scanner into primitive variables or strings using an appropriate method of the

scanner class. Use one of the eight input methods in the table below(The program at the start of these notes uses the next and nextDouble methods.)

Methods for Scanner objectsMethod DescriptionnextByte() Reads an integer of the byte typenextShort() Reads an integer of the short typenextInt() Reads an integer of the int typenextLong() Reads an integer of the long typenextFloat() Reads a number of the float typenextDouble() Reads a number of the double typenext() Reads a string that ends before a whitespacenextLine() Reads a line of characters (i.e., string ending with a

line separator)

A Scanner object reads items separated by whitespaces. A whitespace is one of the following characters: , \t, \f, \r, \n

See www.cs.armstrong.edu/liang/intro8e/book/ComputeAreaWithConsoleInput.java See www.cs.armstrong.edu/liang/intro8e/book/ComputeAverage.java

Page 10: sophiasapiens.chez.comsophiasapiens.chez.com/informatique/Java-Programming…  · Web viewComputer Science Notes. Chapter 2: Elementary Programming. These notes are meant to accompany

Practice:Write a program that prompts a user for a weight in pounds, then converts that weight to kilograms.Note: 1 kg = 2.204 lb.

import java.util.Scanner; // Scanner is in java.util

/** * The MassConversionTool class implements and application * that converts pounds to kilograms. * @author Kevin Mirus * */public class MassConversionTool{

/** * Gets user input for a mass in pounds, then * converts that to kilograms. * @param args */public static void main(String args[]){

}//end method main(String[])}//end class MassConversionTool

import java.util.Scanner; // Scanner is in java.util

/** * The MassConversionTool class implements and application * that converts pounds to kilograms. * @author Kevin Mirus * */public class MassConversionTool{

/** * Gets user input for a mass in pounds, then * converts that to kilograms. * @param args */public static void main(String args[]){

System.out.println("This program converts pounds to kilograms.");

double number_of_pounds;

Scanner keyboard = new Scanner(System.in);

System.out.println("Enter a mass in pounds: ");number_of_pounds = keyboard.nextDouble();

double number_of_kilograms;

number_of_kilograms = number_of_pounds / 2.204;

System.out.println(number_of_pounds + " pounds = " +number_of_kilograms + " kilograms");

}//end method main(String[])}//end class MassConversionTool

Page 11: sophiasapiens.chez.comsophiasapiens.chez.com/informatique/Java-Programming…  · Web viewComputer Science Notes. Chapter 2: Elementary Programming. These notes are meant to accompany

Section 2.4: IdentifiersAn identifier is the name of any programming entity you create, like a variable, constant, method, class,

or package.Rules for naming identifiers: An identifier is a sequence of letters, digits, the underscore ( _ ), or the dollar sign ( $ ). An identifier must start with a letter, underscore ( _ ), or the dollar sign ( $ ). It can not start with a digit. An identifier can not be a reserved word (like class, double, or int). An identifier can not be the words true, false, or null. An identifier can be any length.

Tips for naming identifiers: Identifiers are case sensitive; legA is different from lega. Use descriptive names, like cylinderRadius instead of r for the radius of a cylinder. Use “camel type” or underscores to break up long names into easy-to-recognize pieces, like cylinderRadius or triangle_perimeter. By convention, the $ is only used to start an identifier name in mechanically generated source code. By convention, primitive data type identifiers start with a lower-case letter. By convention, constants are capitalized. By convention, method identifiers start with a lower-case letter. By convention, class identifiers start with an upper -case letter.

Section 2.5: VariablesVariables are used to store data in a program. They can be reassigned new values as many times as you want.

Variables must be declared in Java before they are used so that the JVM can set aside the appropriate amount of memory for the variable. This is because different types of data are stored in different ways and use different amounts of memory, and thus require different algorithms for calculating with them. See the table below for the different primitive data types.

A statement that declares a variable is called a variable declaration.

The syntax for a single variable declaration is:datatype variableName;

Example:double hypotenuse;

The syntax for multiple variable declarations of the same type is:datatype variableName1, variableName2, variableName3, …;

Example:double legA, legB;

To declare and initialize a variable in one statement:datatype variableName1 = value;

Example:double area = 0.0;

Java Primitive Data TypesType Description Sizeint An integer in the range 4 bytes

Page 12: sophiasapiens.chez.comsophiasapiens.chez.com/informatique/Java-Programming…  · Web viewComputer Science Notes. Chapter 2: Elementary Programming. These notes are meant to accompany

-2,147,483,648 int 2,147,483,647These range limits are stored in java.lang.Integer.MIN_VALUEand java.lang.Integer.MAX_VALUE

(32-bit signed)

double Double-precision floating point: 10308 and about 15 significant figuresThese range limits are stored in java.lang.Double.MIN_VALUEand java.lang.Double.MAX_VALUE

8 bytes(64-bit IEEE 754)(1 bit for the sign;11 bits for the exponent;52 bits for the fraction)

char Character type, using Unicode 2 bytesboolean The type with 2 truth values: true and false 1 bitshort A short integer in the range -32768 short 32767

These range limits are stored in java.lang.Short.MIN_VALUEand java.lang.Short.MAX_VALUE

2 bytes(16-bit signed)

long A long integer in the range -9,223,372,036,854,775,808 long 9,223,372,036,854,775,807These range limits are stored in java.lang.Long.MIN_VALUEand java.lang.Long.MAX_VALUE

8 bytes(64-bit signed)

byte -128 byte 127These range limits are stored in java.lang.Byte.MIN_VALUEand java.lang.Byte.MAX_VALUE

1 byte(8-bit signed)

float Single-precision floating point: 1038 and about 7 significant figuresThese range limits are stored in java.lang.Float.MIN_VALUEand java.lang.Float.MAX_VALUE

4 bytes(32-bit IEEE 754)(1 bit for the sign;8 bits for the exponent;23 bits for the fraction)

See: http://en.wikipedia.org/wiki/IEEE_floating-point_standard

Page 13: sophiasapiens.chez.comsophiasapiens.chez.com/informatique/Java-Programming…  · Web viewComputer Science Notes. Chapter 2: Elementary Programming. These notes are meant to accompany

Section 2.6: Assignment Statements and the Assignment ExpressionsAn assignment statement assigns a value to a variable.Java uses the equals sign ( = ) for the assignment operator, or symbol that tells the JVM to store a value in a variable’s memory location.An expression is a collection of values, variables, and operators that represent a computation.Example:

//Calculate the area.area = 0.5 * legA * legB;

//Calculate the perimeter.perimeter = legA + legB + hypotenuse;

A variable can be used in the expression of its own assignment statement. This is quite common…Example:

//increment the variable counter.counter = counter + 1;

An assignment expression is an assignment statement that is part of another statement. The value used by the statement is computed after the assignment is made.Examples:

The assignment expression statement Is equivalent to:System.out.println( x = 1); x = 1;

System.out.println(x);i = j = k = 2; k = 2;

j = k;i = j;

Declaring and Initializing Variables in One StepThe statement Is equivalent to:int j = 5; int j;

j = 5;int j = 5, k = 7; int j, k;

j = 5;k = 7;

Example of an initialization error:int luckyNumber;System.out.println(luckyNumber);// ERROR - uninitialized variable

Page 14: sophiasapiens.chez.comsophiasapiens.chez.com/informatique/Java-Programming…  · Web viewComputer Science Notes. Chapter 2: Elementary Programming. These notes are meant to accompany

Section 2.7: Named Constants A constant represents a value that never changes. To declare a constant, precede its data type with the keyword final. By convention, use capital letters for a constant’s identifier. Constants are a good programming technique because:

o You don’t have to repeatedly type the same number when writing the program.o The value can be changed in a single location, if necessary.o A descriptive name for the constant makes the program easy to read.

Example: Compute the area of a circle.final double PI = 3.1415927;double radius = 2.5;double area;area = radius * radius * PI;

Note: you can access the value of pi to 15 digits using the constant for pi stored in the math class: Math.PI:

double radius = 2.5;double area;area = radius * radius * Math.PI;

Section 2.8: Numeric Data Types and OperationsWe’ll mostly use int and double this semester for numeric variables.Overflow is when you try to assign a value to a variable that is too large for the variable to hold.Underflow is when you try to assign a value to a variable that is too small for the variable to hold.

Section 2.8.1: Numeric Operators

Operator Meaning Example Result+ Addition 34 + 1 35

29.5 + 2.7E2 299.5-88.2 + 5 -83.2

- Subtraction 34 – 0.1 33.9* Multiplication 300 * 30 9000/ Division 1.0 / 2.0 0.5

24 / 2 12Note: integer division only keeps the quotient and discards the remainder

1 / 2 0

% Remainder(integers only)

20 % 3 2

Note: + and – are both unary and binary operators…Note: many simple floating – point numbers do not have an exact binary representation, and thus get rounded off…

System.out.println(1.0 – 0.9);Displays 0.0999999999999998 instead of 0.1

See www.cs.armstrong.edu/liang/intro8e/book/DisplayTime.java

Page 15: sophiasapiens.chez.comsophiasapiens.chez.com/informatique/Java-Programming…  · Web viewComputer Science Notes. Chapter 2: Elementary Programming. These notes are meant to accompany

Practice:Write a program that subtracts two times stated in hours, minutes, and seconds.

/** * The SubtractTimes class implements and application * that subtracts two times given in hours, minutes, and seconds. * @author Kevin Mirus * */public class SubtractTimes{

/** * Gets user input for two times, then * subtracts the times. * @param args */public static void main(String args[]){

}//end method main(String[])}//end class SubtractTimes

import java.util.Scanner;

/** * The SubtractTimes class implements and application * that subtracts two times given in hours, minutes, and seconds. * @author Kevin Mirus * */public class SubtractTimes{

/** * Gets user input for two times, then * subtracts the times. * @param args */public static void main(String args[]){

System.out.println("Enter a later time in hours, " +"minutes, and seconds (separated by spaces): ");

Scanner keyboard = new Scanner(System.in);

int hour1, minute1, second1;hour1 = keyboard.nextInt();minute1 = keyboard.nextInt();second1 = keyboard.nextInt();

System.out.println("The first time is " + hour1 + ":" + minute1 + ":" + second1);

System.out.println("Enter a earlier time in hours, " +"minutes, and seconds (separated by spaces): ");

int hour2, minute2, second2;hour2 = keyboard.nextInt();minute2 = keyboard.nextInt();second2 = keyboard.nextInt();

Page 16: sophiasapiens.chez.comsophiasapiens.chez.com/informatique/Java-Programming…  · Web viewComputer Science Notes. Chapter 2: Elementary Programming. These notes are meant to accompany

System.out.println("The second time is " + hour2 + ":" + minute2 + ":" + second2);

//convert both times to pure secondsint time1 = second1 + minute1 * 60 + hour1 * 3600;int time2 = second2 + minute2 * 60 + hour2 * 3600;

int difference = time1 - time2;

int difference_hours = difference / 3600;int difference_minutes = (difference - difference_hours*3600) / 60;int difference_seconds = difference % 60;

System.out.println("The difference is " + difference_hours + ":" +difference_minutes + ":" + difference_seconds);

}//end method main(String[])}//end class SubtractTimes

Page 17: sophiasapiens.chez.comsophiasapiens.chez.com/informatique/Java-Programming…  · Web viewComputer Science Notes. Chapter 2: Elementary Programming. These notes are meant to accompany

Section 2.8.2: Numeric LiteralsA literal is a constant value that appears in a program.int a = 5; An integer literal is assumed to be an int. For longer integer literals, append an L to the literal: 2147483648L To denote an octal literal, use a zero prefix: 07577 To denote a hexadecimal literal, use a 0x prefix: 0xFFFF A floating-point literal is assumed to be a double. For float literals, append an f or F to the literal: 23.5F The term “floating point” is used for numbers with decimal points because they are always stored usinf scientific notation, where the decimal point is “floated” around. Scientific notation: 1.23456103 = 1.23456e3 = 1.23456e+3; 2.510-4 = 2.5e-4

Section 2.8.3: Evaluating Java Expressions Java follows standard mathematical order of operations See www.cs.armstrong.edu/liang/intro7e/book/FahrenheitToCelsius.java

Practice: Translate the following calculation into Java:

Z = (3 + 4 * x) / 5 – 20 * (y – 5) * (a + b + c) / (3 * x) + 9 * (4 / x + (9 + x) / y);

Section 2.9: Displaying the Current Time The method System.currentTimeMillis() returns a long integer with the number of milliseconds since the Unix epoch began (i.e., January 1, 1970 GMT). See www.cs.armstrong.edu/liang/intro8e/book/ShowCurrentTime.java

Page 18: sophiasapiens.chez.comsophiasapiens.chez.com/informatique/Java-Programming…  · Web viewComputer Science Notes. Chapter 2: Elementary Programming. These notes are meant to accompany

Section 2.10: Shorthand Operators… can be used when the variable in the expression stores the resulting answer…

Operator Meaning Example Equivalent+= Addition Assignment i += 8 i = i + 8-= Subtraction Assignment i -= 8 i = i - 8*= Multiplication

Assignmenti *= 8 i = i * 8

/= Division Assignment i /= 8 i = i / 8%= Remainder Assignment i %= 8 i = i % 8++var Preincrement Increments var by 1 and

uses the new value in var in the expression

var++ Postincrement Uses the old value in var in the expression, then increments var

--var Predecrement Decrements var by 1 and uses the new value in var in the expression

var-- Postdecrement Uses the old value in var in the expression, then decrements var

Section 2.11: Numeric Type ConversionsCasting is an operation that converts one data type into another.Widening a type: casting a variable from a type with a small range to one with a bigger range.Narrowing a type: casting a variable from a type with a large range to one with a smaller range.Widening a type is many times done automatically by the compiler:

1. If one of the operands is a double, then the other is converted to double.2. Otherwise, if one of the operands is a float, then the other is converted to float.3. Otherwise, if one of the operands is a long, then the other is converted to long.4. Otherwise, both operands are converted to int.

Type casting explicitly converts data type by placing desired data type in parentheses in front of variable:int i = 1, j = 3;System.out.println(i / j); //output is 0System.out.println((float)i / (float)j); //output is 0.333333333

public class Test {

/** * @param args */public static void main(String[] args) {

// TODO Auto-generated method stub

int i = 1, j = 3;System.out.println(i / j); //output is 0System.out.println((float)i / (float)j); //output is 0.333333333System.out.println((double)i / (double)j);System.out.println((double)i / j);

}

Page 19: sophiasapiens.chez.comsophiasapiens.chez.com/informatique/Java-Programming…  · Web viewComputer Science Notes. Chapter 2: Elementary Programming. These notes are meant to accompany

}

00.333333340.33333333333333330.3333333333333333

Type casting can be used to round off numbers to a desired number of decimal places. The following example rounds off a monetary amount to two decimals:

See www.cs.armstrong.edu/liang/intro8e/book/SalesTax.java

Page 20: sophiasapiens.chez.comsophiasapiens.chez.com/informatique/Java-Programming…  · Web viewComputer Science Notes. Chapter 2: Elementary Programming. These notes are meant to accompany

Section 2.12: Computing Loan payments See www.cs.armstrong.edu/liang/intro8e/book/ComputeLoan.java

Section 2.13: Character Data Type and OperationsThe data type char is used to represent individual characters.A character literal is enclosed in single quotes.Example:public class CharExample{

public static void main(String[] args){

char letter1 = 'K';char letter2 = 'A';char letter3 = 'M';char numChar = '4';System.out.println("My initials are: " + letter1 + letter2 + letter3);System.out.println("The value of numChar is: " + numChar);System.out.println("One more than numChar is: " + (numChar+1));

}}

My initials are: KAMThe value of numChar is: 4One more than numChar is: 53

Section 2.13.1: Unicode and ASCII code Character encoding is the process of converting a character to its binary representation. How characters are encoded is called an encoding scheme. ASCII is a 7-bit encoding scheme that was meant to display English uppercase and lowercase letters, digits, and punctuation marks. There are 128 ASCII characters. Unicode is the encoding scheme used by Java, and Unicode was meant to display all written characters in all the languages of the world using16 bits (2 bytes), which corresponds to 65,536 characters. This, however, was not enough choices for all the characters in the world. 16-bit Unicode characters are accessed in quotes with a \u followed by four hexadecimal digits. Supplementary Unicode represents all the characters that go beyond the 16-bit limit, and will not be discussed in this class. See www.cs.armstrong.edu/liang/intro8e/book/DisplayUnicode.java

Page 21: sophiasapiens.chez.comsophiasapiens.chez.com/informatique/Java-Programming…  · Web viewComputer Science Notes. Chapter 2: Elementary Programming. These notes are meant to accompany

Section 2.13.2: Escape Sequences for Special CharactersEscape sequences are designed to display special characters in string literals.Escape sequences are preceded by a backslash

public class EscapeSequenceExample{

public static void main(String[] args){

System.out.println("He said \"Java is Fun\".\n\"Java is Fun.\"");}

}

He said "Java is Fun"."Java is Fun."

\b backspace\t tab\n linefeed\f formfeed\r carriage return\\ backslash\’ single quote\” double quoteSection 2.13.3: Casting Between char and Numeric Data Types When an integer is cast to a char, only the lower 16 bits of data are used.

Page 22: sophiasapiens.chez.comsophiasapiens.chez.com/informatique/Java-Programming…  · Web viewComputer Science Notes. Chapter 2: Elementary Programming. These notes are meant to accompany

When a float or double is cast to a char, the floating-point value is cast to an int, which is then cast to a char.When a char is cast to a numeric type, the character’s Unicode value is cast to the specified numeric type.

Section 2.14: Problem: Counting Monetary Units See www.cs.armstrong.edu/liang/intro8e/book/ComputeChange.java

Section 2.15: The String Type The data type of String is used to store a string (or sequence) of characters.The String type is not a primitive data type; it is a reference type (more about that later…).Strings can be concatenated with the + operator.

public class StringExamples{

public static void main(String[] args){

String message1 = "Welcome to Java.";String message2 = "Welcome " + "to " + "Java.";System.out.println("message1 = " + message1);System.out.println("message2 = " + message2);System.out.println();

String message3 = "Chapter " + 2;String message4 = "Supplement " + 'B';System.out.println("message3 = " + message3);System.out.println("message4 = " + message4);System.out.println();

message2 += " Java is fun!";System.out.println("message2 = " + message2);System.out.println();

int i = 2, j = 3;System.out.println("i = " + i);System.out.println("j = " + j);System.out.println("concatenation: i + j = " + i + j);System.out.println("addition: i + j = " + (i + j));

}}

message1 = Welcome to Java.message2 = Welcome to Java.

message3 = Chapter 2message4 = Supplement B

message2 = Welcome to Java. Java is fun!

i = 2j = 3concatenation: i + j = 23addition: i + j = 5

Also see http://faculty.matcmadison.edu/kmirus/20092010A/804208/804208LP/Chap02StringBasics.java

Page 23: sophiasapiens.chez.comsophiasapiens.chez.com/informatique/Java-Programming…  · Web viewComputer Science Notes. Chapter 2: Elementary Programming. These notes are meant to accompany

Section 2.16: Programming Style and Documentation Programming style deals with how the source code to a program looks: Documentation is the body of explanatory remarks and comments pertaining to a program.

Section 2.16.1: Appropriate Comments and Comment Styles At the start of a program, include a summary of what the program does, its key features, its supporting data structures, and any unique techniques it uses. A long program should also have comments that introduce each major step and explain anything that is difficult to read. javadoc comments ( /** … */ ) are used to give information about classes, methods, and public variables. Comments of this type can be read by the javadoc utility program which generates HTML support documents from them.

Section 2.16.2: Naming Conventions Use descriptive names with straightforward meanings for your variables, constants, classes, and methods. Names are case-sensitive. Start the names of primitive variables, objects, and methods with a lowercase letter. Start the names of classes with an uppercase letter. Capitalize every letter in the name of a constant.

Section 2.16.3: Proper Indentation and Spacing Indent lines of code by the same amount that are at the same “nesting level” in a program. Put a single blank space on either side of a binary operator.

Page 24: sophiasapiens.chez.comsophiasapiens.chez.com/informatique/Java-Programming…  · Web viewComputer Science Notes. Chapter 2: Elementary Programming. These notes are meant to accompany

Section 2.16.4: Block Styles A block is a group of statements surrounded by (curly) braces, { }. In end-of-line style, the opening brace for the block is at the end of the line. In next-line style, the opening brace for the block is at the start of the next line.

/**Here is a simple program written using the end-of-line block style. */

public class BlockStyleTest {public static void main(String[] args) {

System.out.println("Block Styles.");}

}

/**Here is a simple program written using the next-line block style. */public class BlockStyleTest{

public static void main(String[] args){

System.out.println("Block Styles.");}

}

Section 2.17: Programming ErrorsSection 2.17.1: Syntax Errors

A syntax error is an error that occurs during program compilation. Syntax errors result from errors in code construction, like mistyping a keyword, omitting necessary

punctuation, not declaring a variable before it is used, or having unmatched pairs of braces or parentheses.

Eclipse shows you your syntax errors with a red x in front of the offending line.

Section 2.17.2: Runtime Errors A runtime error is an error that occurs during program execution. Runtime errors result when the program is supposed to perform an operation that is impossible to carry

out, like divide by zero, open a disk file that does not exist, or store a letter in a floating-point data type, etc.

Section 2.17.3: Logic Errors A logic error is an error that occurs because the code you wrote is not logically consistent with what you

wanted the program to do. Logic errors can result when you type the wrong variable name, or do any one of ten million other bone-

headed things.

Section 2.17.4: Debugging Debugging is the process of finding errors in your code and correcting them. Syntax errors are usually easier to debug, because the compiler tells you which lines of code have syntax errors. Runtime errors are also fairly easy to debug, because the program will crash with an error message telling you which line of code caused the error. Logic errors are tough to debug, because they do not cause any visible problems.

o Logic errors can be debugged by hand by hand-tracing through the lines of code in a program, keeping track of variable values, and seeing where things go wrong.

Page 25: sophiasapiens.chez.comsophiasapiens.chez.com/informatique/Java-Programming…  · Web viewComputer Science Notes. Chapter 2: Elementary Programming. These notes are meant to accompany

o Logic errors can also be traced using a debugger utility, like the jdb command-line debugger in the JDK.

o Eclipse also has a built-in debugger, which allows you to Execute code a single line at a time Trace into or step over methods Set breakpoints where the program stops and lets you look at execution a line at a time Display variables Display call stacks Modify variables

Section 2.18: (GUI) Getting Input from Dialog Boxes

The JOptionPane class has a method called showInputDialog that creates a GUI (Graphical User Interface) dialog box for reading in data. It basically provides a window with a title in a title bar, an icon in the title bar, a close button in the title bar, and an icon, text prompt, text box, an OK button, and a Cancel button. The showInputDialog method returns a string copy of what was typed into the text box.

Here is the program from the start of these notes re-written using dialog boxes:

import javax.swing.JOptionPane;// The import statement tells the compiler where to find the JOptionPane class,// which contains the code for dialog boxes.

/**The Chap02BasicsGUI class implements an application that * illustrates the basics of computer programming: * retrieving user input, performing calculations, * and generating output using a GUI interface of dialog boxes. * Specifically, this program computes the area, hypotenuse, and perimeter * of a right triangle, given the lengths of the two legs. * This is meant as an example of the material in Chapter 2 of the text * _Introduction to Java Programming: Brief Version_, 7th ed. by Y. D. Liang * @author Kevin Mirus */

public class Chap02BasicsGUI{

/** Calculates the area, hypotenuse, and perimeter of a right triangle, * given the lengths of the two legs. * @param args is not used. */public static void main(String[] args){

//Tell the user what the program doesJOptionPane.showMessageDialog(null, "This program will calculate " +

"the hypotenuse, perimeter, and area of a right triangle " +"given the lengths of its legs.", "Chap02BasicsGUI Intro",JOptionPane.INFORMATION_MESSAGE);

// ********************************************************************// Here is the portion of the code that reads data into memory.// ********************************************************************//Declare variables for the data to be read in: i.e., the lengths of the two

legsdouble legA, legB;

//Input dialog boxes return strings as output, so we also need a String object//for each numeric variable, which will then get converted to doubles.String legA_String, legB_String;

Page 26: sophiasapiens.chez.comsophiasapiens.chez.com/informatique/Java-Programming…  · Web viewComputer Science Notes. Chapter 2: Elementary Programming. These notes are meant to accompany

//Declare a String object to store the user's name.String userName;

//Prompt the user for his/her name, and store in userNameuserName = JOptionPane.showInputDialog(null, "Please enter your name.",

"Your name", JOptionPane.QUESTION_MESSAGE);

//Prompt the user for the length of the first leg.legA_String = JOptionPane.showInputDialog(null, "Please enter the " +

"length of the first leg of the right triangle:", "First Leg",JOptionPane.QUESTION_MESSAGE);

//Convert the string from the input dialog box to a double-precision//number, and store the answer in legAlegA = Double.parseDouble(legA_String);

//Prompt the user for the length of the second leg,//then convert the string to a number and store in legBlegB_String = JOptionPane.showInputDialog(null, "Please enter the " +

"length of the second leg of the right triangle:", "Second Leg",JOptionPane.QUESTION_MESSAGE);

legB = Double.parseDouble(legB_String);

// ********************************************************************// Here is the portion of the code that// performs calculations on the data in memory.// ********************************************************************//Declare variables for the quantities to be read calculated.double hypotenuse, perimeter , area;

//Calculate the hypotenuse using the Pythagorean Theorem:// a^2 + b^2 = c^2// c = sqrt(a^2 + b^2)hypotenuse = Math.sqrt(legA*legA + legB*legB);

//Calculate the perimeter by adding up the lengths of the three sides.perimeter = legA + legB + hypotenuse;

//Calculate the area using the formula area = (1/2)(base)(height).area = 0.5 * legA * legB;

// ********************************************************************// Here is the portion of the code that displays// memory values for output.// ********************************************************************//Report the results for hypotenuseString hypotenuseString = "Okay, " + userName + ", the hypotenuse of your "

+ "right triangle is: " + hypotenuse;JOptionPane.showMessageDialog(null, hypotenuseString, "Hypotenuse Results",

JOptionPane.INFORMATION_MESSAGE);

//Report the results for perimeterString perimeterString = "The perimeter of your right triangle is: " +

perimeter;JOptionPane.showMessageDialog(null, perimeterString, "Perimeter Results",

JOptionPane.INFORMATION_MESSAGE);

//Report the results for areaString areaString = "The area of your right triangle is: " + area;

Page 27: sophiasapiens.chez.comsophiasapiens.chez.com/informatique/Java-Programming…  · Web viewComputer Science Notes. Chapter 2: Elementary Programming. These notes are meant to accompany

JOptionPane.showMessageDialog(null, areaString, "Area Results",JOptionPane.INFORMATION_MESSAGE);

//Tell the user that the program is done.JOptionPane.showMessageDialog(null, "I hope you enjoyed your results.", "All

Done",JOptionPane.INFORMATION_MESSAGE);

}//end of main(String[])}//end of class Chap02BasicsGUI

Page 28: sophiasapiens.chez.comsophiasapiens.chez.com/informatique/Java-Programming…  · Web viewComputer Science Notes. Chapter 2: Elementary Programming. These notes are meant to accompany
Page 29: sophiasapiens.chez.comsophiasapiens.chez.com/informatique/Java-Programming…  · Web viewComputer Science Notes. Chapter 2: Elementary Programming. These notes are meant to accompany

Section 2.18.1: Converting Strings to NumbersIf a string contains a sequence of characters meant to represent a number, then you can convert that string to a number using either the parseInt method of the Integer class, or the parseDouble method of the Double class.

String stringX = "123";int x = Integer.parseInt(stringX);System.out.println("x + 5 = " + (x + 5));

String stringY = "456.789";double y = Double.parseDouble(stringY);System.out.println("y + 5 = " + (y + 5));

Section 2.18.2: Using Input Dialog Boxes

Also see www.cs.armstrong.edu/liang/intro8e/book/ComputeLoanUsingInputDialog.java