Upload
irma-lee
View
224
Download
0
Tags:
Embed Size (px)
Citation preview
Variable DeclarationVariable Declaration
It is possible to declare multiple variables It is possible to declare multiple variables of the same data type on the same line.of the same data type on the same line. Ex. Ex.
double hours, rate, total;double hours, rate, total;
Variables may also be initialized during Variables may also be initialized during multiple declarationsmultiple declarations Ex. Ex.
double hours = 35.5, rate = 8.0, total;double hours = 35.5, rate = 8.0, total;
Variable and ConstantsVariable and Constants
It is possible to give a variable a starting It is possible to give a variable a starting value when it is declared.value when it is declared.Ex.Ex. int x=7;int x=7;
float y=2.345;float y=2.345;
char initial = ‘K’; char initial = ‘K’;
Another variation is to create a constant Another variation is to create a constant (i.e. a value that cannot change (i.e. a value that cannot change throughout a program)throughout a program)
Ex.Ex. final int MAXAGE = 65;final int MAXAGE = 65;
Arithmetic OperatorsArithmetic Operators
AddAdd
SubtractSubtract
MultiplyMultiply
DivideDivide
Modulus (remainder)Modulus (remainder)
++
--
**
//
%%
Order of OperationsOrder of Operations
All operators within parentheses are All operators within parentheses are performed firstperformed first
If there are nested parentheses If there are nested parentheses (parentheses within parentheses) the (parentheses within parentheses) the innermost operators are performedinnermost operators are performed
The *,/,% operators are performed next, The *,/,% operators are performed next, from left to rightfrom left to right
The + and - are performed last from left to The + and - are performed last from left to right. right.
Assignment StatementAssignment Statement
An assignment statement is used to assign a An assignment statement is used to assign a value on the left hand side of an equation to a value on the left hand side of an equation to a variable on the right.variable on the right.
The command used to create an assignment The command used to create an assignment statement is the equals sign(=).statement is the equals sign(=).
The general form of an assignment statement The general form of an assignment statement is:is:<variable> = <expression>;<variable> = <expression>;
Compound Assignment Compound Assignment OperationsOperations
Simple AssignmentSimple Assignment
Compound AdditionCompound Addition
Compound SubtractionCompound Subtraction
Compound MultiplicationCompound Multiplication
Compound DivisionCompound Division
Compound RemainderCompound Remainder
==
+=+=
-=-=
*=*=
/=/=
%=%=(integers only)
Compound Assignment Compound Assignment EqualitiesEqualities
x = x + 10x = x + 10
x = x – 10x = x – 10
x = x * 10x = x * 10
x = x / 10x = x / 10
x = x % 10x = x % 10
x += 10x += 10
x –= 10x –= 10
x *= 10x *= 10
x /= 10x /= 10
x %= 10x %= 10
Increment and Increment and Decrement OperatorsDecrement Operators
Increment and Decrement operators add Increment and Decrement operators add one or subtract one to the value of the one or subtract one to the value of the variable.variable.
Can be applied to integer, floating point, Can be applied to integer, floating point, or character variables.or character variables.
INCREMENT ++INCREMENT ++ DECREMENT --DECREMENT --
Numeric Type Numeric Type Conversion(TypeCasting)Conversion(TypeCasting)
When you perform arithmetic operations with When you perform arithmetic operations with operands of unlike types, the Java language chooses operands of unlike types, the Java language chooses a unifying type for the result.a unifying type for the result.
The Java programming language then converts The Java programming language then converts nonconforming operands to the unifying type. This nonconforming operands to the unifying type. This unifying type is the type of the involved operand that unifying type is the type of the involved operand that appears first in the following list:appears first in the following list:
1.1. doubledouble2.2. floatfloat3.3. longlong4.4. intint5.5. shortshort6.6. bytebyte
Typecasting (cont.)Typecasting (cont.)
If you do not want this to happen you have to If you do not want this to happen you have to purposely override the unifying type purposely override the unifying type (typecasting)(typecasting)
Ex:Ex:int balance= 189;int balance= 189;double weeklyBudget = (double)balance/4;double weeklyBudget = (double)balance/4;
//weeklyBudget will be 47.25//weeklyBudget will be 47.25int dollars = (int) weeklyBudget;int dollars = (int) weeklyBudget;
//dollars will be 47//dollars will be 47
Strings and Object-Strings and Object-Oriented TypesOriented Types
Simple data types are used when simple Simple data types are used when simple calculations need to be done.calculations need to be done.
For more advanced applications, there is a need For more advanced applications, there is a need for strings and object-oriented types.for strings and object-oriented types.
These types can give the application the ability to These types can give the application the ability to (for example) “turn the power on”, “signal if a seat (for example) “turn the power on”, “signal if a seat belt is not attached”, “regulate the fuel mixture in an belt is not attached”, “regulate the fuel mixture in an engine”engine”
These data type classes are called class wrappers These data type classes are called class wrappers or object wrappers.or object wrappers.
String Data TypeString Data Type
String is used to contain more than one character.String is used to contain more than one character. The stored characters must be placed in double The stored characters must be placed in double
quotes.quotes. Many times, processing all input as strings Many times, processing all input as strings
improves reliability of a program because the improves reliability of a program because the computer can take in a series of characters, test computer can take in a series of characters, test them to see if they are numbers, and then work them to see if they are numbers, and then work with them.with them.
Ex:Ex:String name=“Rusty”;String name=“Rusty”;
String ConcatenationString Concatenation String concatenation is used to combine strings String concatenation is used to combine strings
and strings or strings and variables together.and strings or strings and variables together.Ex. Ex.
String firstName, lastName, lastFirst;String firstName, lastName, lastFirst;
int age = 65;int age = 65;firstName = “John”;firstName = “John”;lastName = “Doe;lastName = “Doe;lastFirst = lastName + “ “ + firstName + “ is age “ + age;lastFirst = lastName + “ “ + firstName + “ is age “ + age;System.out.println (lastFirst);System.out.println (lastFirst);System.out.println(firstName + “ is: \n” + age + “ years old”);System.out.println(firstName + “ is: \n” + age + “ years old”);
Output:Output:Doe John is age 65Doe John is age 65John is John is 65 years old65 years old
Methods in class Methods in class KeyboardReaderKeyboardReaderSignature Description
char readChar() Returns the first character in the input line, even if it is a space.
double readDouble() Returns the first double in the input line. Leading and trailing spaces will be ignored.
int readInt() Returns the first integer in the input line. Leading and trailing spaces are ignored
String readLine() Returns the input line, including leading and trailing spaces
void pause() Returns once the user presses Enter.
ErrorsErrors
There are three types of errors in programming: syntax, There are three types of errors in programming: syntax, run-time, and logical errors.run-time, and logical errors.
Syntax errors occur when you violate a syntax rule (i.e Syntax errors occur when you violate a syntax rule (i.e using system.Out.println instead of System.out.println).using system.Out.println instead of System.out.println).
Run-time errors occur when you ask a computer to do Run-time errors occur when you ask a computer to do something it cannot do (i.e divide by zero).something it cannot do (i.e divide by zero).
Logic errors occur when you fail to express yourself Logic errors occur when you fail to express yourself accurately (i.e using greater than instead of less than)accurately (i.e using greater than instead of less than)
Example ProgramExample Programpublic class Example2{
public static void main (String[] args){
int oneint=10;int twoint=15;int sum,difference,product, modulus;float quotient;
System.out.print("The first int is ");System.out.println(oneint);
System.out.println("The second int is " + twoint);
sum = oneint + twoint;difference = oneint - twoint;product = oneint * twoint;modulus = oneint % twoint;quotient = oneint / (float)twoint;
System.out.println("The sum is " + sum);System.out.println("The difference is " + difference);System.out.println("The product is " + product);System.out.println("The quotient is " + quotient);System.out.println("The modulus is " + modulus);
}}
Math ClassMath Class The math class is quite extensive but we will The math class is quite extensive but we will
concentrate a just a few of it’s properties:concentrate a just a few of it’s properties:abs(int x)abs(int x) Returns the absolute value of xReturns the absolute value of x
pow(double base, double pow(double base, double exponent)exponent)
Returns the base raised to the exponent.Returns the base raised to the exponent.
round(double x)round(double x) Returns x rounded to the nearest whole Returns x rounded to the nearest whole number.number.
max(int a , int b)max(int a , int b) Returns the greater of a and bReturns the greater of a and b
min(int a , int b)min(int a , int b) Returns the lesser of a and bReturns the lesser of a and b
random()random() Returns a double value with a positive sign, Returns a double value with a positive sign,
greater than or equal to 0.0 and less than 1.0.greater than or equal to 0.0 and less than 1.0.
sqrt(double x)sqrt(double x) Returns the square root of x.Returns the square root of x.
Examples of Math Class Examples of Math Class MethodsMethods
int m;int m;
double x;double x;
m = Math.abs(-7) m = Math.abs(-7) // m equals 7// m equals 7
x = Math.abs(-7.5)x = Math.abs(-7.5) // x equals 7.5// x equals 7.5
x = Math.pow(3.0,2.0)x = Math.pow(3.0,2.0) // x equals 3.0^2.0 = 9.0// x equals 3.0^2.0 = 9.0
x = Math.pow(16.0, .25)x = Math.pow(16.0, .25) // x equals 16.0 ^ .25 = 2.0// x equals 16.0 ^ .25 = 2.0
m = Math.max(20,40)m = Math.max(20,40) // m equals 40// m equals 40
m = Math.min(20,40)m = Math.min(20,40) // m equals 20// m equals 20
m = (int) Math.round(4.27)m = (int) Math.round(4.27) // m equals 4// m equals 4
Math.randomMath.random
In order to generate a random number between In order to generate a random number between a certain range use the following formula.a certain range use the following formula. X = Math.random() * (high # - low #) + low #X = Math.random() * (high # - low #) + low #
If you want the number to be an integer, you If you want the number to be an integer, you must use the round function. must use the round function. X = Math.round(Math.random() * (high # - low #) + low #)X = Math.round(Math.random() * (high # - low #) + low #)
Or typecast the formula + 1 to an intOr typecast the formula + 1 to an int X = (int)(Math.random() * (high # - low # + 1) + low #)X = (int)(Math.random() * (high # - low # + 1) + low #)
Random ClassRandom Class
Must include Must include import java.util.Random;import java.util.Random;
Must then create an object from Random Must then create an object from Random classclass Ex: Random Ex: Random name name = new Random();= new Random();
Use object to call methodsUse object to call methods Ex: Ex: namename..method();method();
Random Class MethodsRandom Class Methods
nextIntnextInt(integer);(integer); Generates a random whole number between Generates a random whole number between
0-(0-(integer -1)integer -1)
nextDouble();nextDouble(); Generates a random decimal between Generates a random decimal between
0.0 – 1.00.0 – 1.0