fundamentals 2 chapter 2. operators operators are special symbols used for: mathematical functions...

33
FUNDAMENTALS 2 CHAPTER 2

Upload: beryl-foster

Post on 13-Dec-2015

227 views

Category:

Documents


0 download

TRANSCRIPT

FUNDAMENTALS 2CHAPTER 2

OPERATORS

Operators are special symbols used for: mathematical functions assignment statements logical comparisons

Examples of operators: 3 + 5 // uses + operator 14 + 5 – 4 * (5 – 3) // uses +, -, * operators

Expressions: can be combinations of variables and operators that result in a value

GROUPS OF OPERATORS

There are 5 different groups of operators: Arithmetic Operators

Assignment Operator

Increment / Decrement Operators

Relational Operators

Logical Operators

JAVA ARITHMETIC OPERATORS

Addition +

Subtraction –

Multiplication

Division /

Remainder (modulus ) %

Assignment Operator =

ARITHMETIC OPERATORS The following table summarizes the arithmetic operators

available in Java.

EXAMPLEExample of division issues:

10 / 3 gives 3

10.0 / 3 gives 3.33333

As we can see,

•if we divide two integers we get an integer result.

•if one or both operands is a floating-point value we get a floating-point result.

MODULUS

Generates the remainder when you divide two integer values.

5%3 gives 2 5%4 gives 1

5%5 gives 0 5%10 gives 5

Modulus operator is most commonly used with integer operands. If we attempt to use the modulus operator on floating-point values we will garbage!

EXAMPLE: SUM OF TWO INTEGER public class Sum { // main method public static void main( String args[] ){ int a, b, sum; a = 20;

b = 10; sum = a + b; System.out.println(a + ” + ” + b + “ = “ + sum);

} // end main } // end class Sum

ARITHMETIC/ASSIGNMENT OPERATORS

Java allows combining arithmetic and assignment operators into a single operator:

Addition/assignment +=

Subtraction/assignment -=

Multiplication/assignment =

Division/assignment /=

Remainder/assignment %=

INCREMENT/DECREMENT OPERATORS

Only use ++ or   when a variable is being incremented/decremented as a statement by itself.

x++; is equivalent to x = x+1;

x--; is equivalent to x = x-1;

RELATIONAL OPERATORS

Operation Is true when

a >b a is greater than b

a >=b a is greater than or equal to b

a ==b a is equal to b

a !=b a is not equal to b

a <=b a is less than or equal to b

a <b a is less than b

Relational operators compare two values

They Produce a boolean value (true or false) depending on the relationship

EXAMPLE

int x = 3;

int y = 5;

boolean result;

result = (x > y);

now result is assigned the value false because 3 is not greater than 5

LOGICAL OPERATORS

|| T F

T T T

F T F

Symbol Name

&& AND

|| OR

! NOT

&& T F

T T F

F F F

EXAMPLE

boolean x = true;

boolean y = false;

boolean result;

result = (x && y);

result is assigned the value false

result = ((x || y) && x);

(x || y) evaluates to true

(true && x) evaluates to true

result is then assigned the value true

OPERATORS PRECEDENCE

Parentheses (), inside-out

Increment/decrement ++, --, from left to right

Multiplicative *, /, %, from left to right

Additive +, -, from left to right

Relational <, >, <=, >=, from left to right

Equality ==, !=, from left to right

Logical AND &&

Logical OR ||

Assignment =, +=, -=, *=, /=, %=

INPUT & OUTPUT

INPUT AND SYSTEM.IN

System.out

An object with methods named println and print

System.in

not intended to be used directly

We use a second object, from a class Scanner, to help us.

Constructing a Scanner object to read console input:

Scanner name = new Scanner(System.in);

Example:

Scanner console = new Scanner(System.in);

STANDARD OUTPUT WINDOW

Using System.out, we can output multiple lines of text to the standard output window.

• The exact style of standard output window depends on the Java tool you use.

THE PRINTLN METHOD

We use println instead of print to skip a line.

int x = 123, y = x + x;System.out.print( " x = “ );System.out.println( x );System.out.print( " x + x = “ );System.out.println( y );System.out.println( " THE END“ );

x = 123 x + x = 246 THE END

STANDARD INPUT

To input primitive data values, we use the Scanner class.

4 steps are needed to be able to use input primitive: Step 1: import the Scanner class:

import Java.util.Scanner;

Step 2 : declaring a reference variable of a Scanner Scanner read ; //we named the object read

Step 3: creating an instance of the Scanner read = new Scanner (System.in);

Step 4: use specific methods to enter data int x = read.nextInt();

JAVA CLASS LIBRARIES, IMPORT Java class libraries: Classes included with Java's JDK.

organized into groups named packages

To use a package, put an import declaration in your program.

Syntax:

// put this at the very top of your program

import packageName.*;

Scanner is in a package named java.util

import java.util.*;

import java.util.Scanner;

To use Scanner, you must place the above line at the top of your program (before the public class header).

SCANNER METHODS

Each method waits until the user presses Enter.The value typed is returned.System.out.print("How old are you? "); // promptint age = console.nextInt();System.out.println("You'll be 40 in " + (40 - age) + " years.");

prompt: A message telling the user what input to type.

Method Description

nextInt() reads a token of user input as an int

nextDouble() reads a token of user input as a double

next() reads a token of user input as a String

nextLine() reads a line of user input as a String

COMMON SCANNER METHODS

Method Example

Scanner input = new Scanner (System.in);

nextByte( ) byte b = input.nextByte( );

nextDouble( ) double d = input.nextDouble( );

nextFloat( ) float f = input.nextFloat( );

nextInt( ) int i = input.nextInt( );

nextLong( ) long l = input.nextLong( );

nextShort( ) short s = input.nextShort( );

next() String str = input.next();

EXAMPLE SCANNER USAGEimport java.util.*; // so that I can use Scanner

public class ReadSomeInput {

public static void main(String[] args) {

Scanner console = new Scanner(System.in);

System.out.print("How old are you? ");

int age = console.nextInt();

System.out.println(age + "... That's quite old!");

}

}

Output (user input underlined):

How old are you? 14

14... That's quite old!

ANOTHER SCANNER EXAMPLE

import java.util.*; // so that I can use Scanner

public class ScannerSum {

public static void main(String[] args) {

Scanner console = new Scanner(System.in);

System.out.print("Please type three numbers: ");

int num1 = console.nextInt();

int num2 = console.nextInt();

int num3 = console.nextInt();

int sum = num1 + num2 + num3;

System.out.println("The sum is " + sum);

}

}

Output (user input underlined):

Please type three numbers: 8 6 13

The sum is 27

The Scanner can read multiple values from one line.

INPUT TOKENS

token: A unit of user input, as read by the Scanner.

Tokens are separated by whitespace (spaces, tabs, newlines).

How many tokens appear on the following line of input?23 John Smith 42.0 "Hello world" $2.50 " 19"

When a token is not the type you ask for, it crashes.

System.out.print("What is your age? ");

int age = console.nextInt();

Output:

What is your age? Timmy

java.util.InputMismatchException

at java.util.Scanner.next(Unknown Source)

at java.util.Scanner.nextInt(Unknown Source)

...

EXAMPLE

import java.util.Scanner;

public class TestInput {public static void main(String[] args) {Scanner input ; int area ,length, width; input = new Scanner (System.in); // creating an instance

System.out.println("enter the length "); length = input.nextInt(); //reading the length from the

keyboard

System.out.println("Enter the Width "); width = input.nextInt(); //reading the width from the

keyboard

area = length * width ;

System.out.println("the length is "+ length);System.out.println("the width is "+ width);System.out.println("the area is "+ area);

}}

OUTPUT

enter the length

2

Enter the Width

3

the length is 2

the width is 3

the area is 6

29

COMMONLY USED ESCAPE SEQUENCES

PARSING

31

PARSING NUMERIC STRINGS Integer, Float, and Double are classes designed to convert a

numeric string into a number. These classes are called wrapper classes.

parseInt is a method of the class Integer, which converts a numeric integer string into a value of the type int.

parseFloat is a method of the class Float and is used to convert a numeric decimal string into an equivalent value of the type float.

parseDouble is a method of the class Double, which is used to convert a numeric decimal string into an equivalent value of the type double.

32

PARSING NUMERIC STRINGS

A string consisting of only integers or decimal numbers is called a numeric string.

To convert a string consisting of an integer to a value of the type int, we use the following expression:

Integer.parseInt(strExpression)• Example:

Integer.parseInt("6723") = 6723Integer.parseInt("-823") = -823

33

PARSING NUMERIC STRINGS

To convert a string consisting of a decimal number to a value of the type float, we use the following expression:

Float.parseFloat(strExpression)• Example:

Float.parseFloat("34.56") = 34.56Float.parseFloat("-542.97") = -542.97

To convert a string consisting of a decimal number to a value of the type double, we use the following expression:

Double.parseDouble(strExpression)• Example:

Double.parseDouble("345.78") = 345.78Double.parseDouble("-782.873") = -782.873