Java in pictures (lection2 ) 1 Java in pictures Lection2. Dudnik O.A.

Презентация:



Advertisements
Похожие презентации

Advertisements

1. Определить последовательность проезда перекрестка
Таблица умножения на 8. Разработан: Бычкуновой О.В. г.Красноярск год.
Фрагмент карты градостроительного зонирования территории города Новосибирска Масштаб 1 : 6000 Приложение 7 к решению Совета депутатов города Новосибирска.
1 Знаток математики Тренажер Таблица умножения 2 класс Школа 21 века ®м®м.
Фрагмент карты градостроительного зонирования территории города Новосибирска Масштаб 1 : 6000 Приложение 7 к решению Совета депутатов города Новосибирска.
Урок повторения по теме: «Сила». Задание 1 Задание 2.
Фрагмент карты градостроительного зонирования территории города Новосибирска Масштаб 1 : 4500 к решению Совета депутатов города Новосибирска от
Object-Oriented Programming Ramzi Saifan Program Control Slides adapted from Steven Roehrig.
Прототип задания В3 Площади фигур. Задание 1 Задание 2.
1 Знаток математики Тренажер Таблица умножения 3 класс Школа России Масько Любовь Георгиевна Муниципальное общеобразовательное учреждение средняя общеобразовательная.
П РОТОТИП ЗАДАНИЯ В3 В МАТЕРИАЛАХ ЕГЭ Площади фигур.
Масштаб 1 : Приложение 1 к решению Совета депутатов города Новосибирска от _____________ ______.
1/27 Chapter 9: Template Functions And Template Classes.
Лекция 2 Раздел 2.1 Windows Phone Темы раздела 3.
Масштаб 1 : Приложение 1 к решению Совета депутатов города Новосибирска от
Отделение ПФР по Тамбовской области Проведение кампании по повышению пенсионной грамотности молодежи в Тамбовской области в 2011 году 8 февраля 2012 г.
Structured Error Handling in the ABL Sarah Marshall QA Architect, OpenEdge Session 128.
ЦИФРЫ ОДИН 11 ДВА 2 ТРИ 3 ЧЕТЫРЕ 4 ПЯТЬ 5 ШЕСТЬ 6.
Развивающая викторина для детей "Самый-самый " Муниципальное общеобразовательное учреждение средняя общеобразовательная школа 7 ст. Беломечётской.
Транксрипт:

Java in pictures (lection2 ) 1 Java in pictures Lection2. Dudnik O.A.

Java in pictures (lection2 )2

3 Package Java.lang.*; String StringBuffer StringBuilder Thread Throwable Class Object Number (Wrapper s) Error Exceptions Math Class System

Java in pictures (lection2 )4 Базовый класс Object в java. 1. public final native Class getClass() 2. public native int hashCode() 3. public boolean equals(Object obj) 4. protected native Object clone() throws CloneNotSupportedException 5. public String toString() 6. public final native void notify() 7. public final native void notifyAll() 8. public final native void wait(long timeout) throws InterruptedException 9. public final void wait(long timeout, int nanos) throws InterruptedException 10. public final void wait() throws InterruptedException 11. protected void finalize() throws Throwable 4

Java in pictures (lection2 )5

6

7

8

9 Пакет java.lang.*; import java.lang.*;//по умолчанию import java.lang.*;//по умолчанию

Java in pictures (lection2 )10

Java in pictures (lection2 )11

Java in pictures (lection2 )12 Class Number

Java in pictures (lection2 )13 Boxing & unboxing

Java in pictures (lection2 )14 Class Math

Java in pictures (lection2 )15

Java in pictures (lection2 )16

Java in pictures (lection2 )17

Java in pictures (lection2 )18

Java in pictures (lection2 )19 Операторы ввода-вывода Class System java.lang.System.out.print(Text); java.lang.System.out.print(Text); java.lang.System.out.println(Continue text); java.lang.System.out.println(Continue text); Scanner scanner= new Scanner(new InputStreamReader(System.in)); Scanner scanner= new Scanner(new InputStreamReader(System.in)); BufferedReader buf = new BufferedReader(new InputStreamReader(System.in)); BufferedReader buf = new BufferedReader(new InputStreamReader(System.in));

Java in pictures (lection2 )20 public class SwapElementsExample { public class SwapElementsExample { public static void main(String[] args) { public static void main(String[] args) { int num1 = 10; int num1 = 10; int num2 = 20; int num2 = 20; System.out.println("Before Swapping"); System.out.println("Before Swapping"); System.out.println("Value of num1 is :" + num1); System.out.println("Value of num1 is :" + num1); System.out.println("Value of num2 is :" +num2); System.out.println("Value of num2 is :" +num2); //swap the value //swap the value swap(num1, num2); swap(num1, num2); } } private static void swap(int num1, int num2) { private static void swap(int num1, int num2) { int temp = num1; int temp = num1; num1 = num2; num1 = num2; num2 = temp; num2 = temp; System.out.println("After Swapping"); System.out.println("After Swapping"); System.out.println("Value of num1 is :" + num1); System.out.println("Value of num1 is :" + num1); System.out.println("Value of num2 is :" +num2); System.out.println("Value of num2 is :" +num2);

Java in pictures (lection2 )21 public class SwapElementsWithoutThirdVariableExample { public class SwapElementsWithoutThirdVariableExample { public static void main(String[] args) { public static void main(String[] args) { int num1 = 10; int num1 = 10; int num2 = 20; int num2 = 20; System.out.println("Before Swapping"); System.out.println("Before Swapping"); System.out.println("Value of num1 is :" + num1); System.out.println("Value of num1 is :" + num1); System.out.println("Value of num2 is :" +num2); System.out.println("Value of num2 is :" +num2); //add both the numbers and assign it to first //add both the numbers and assign it to first num1 = num1 + num2; num1 = num1 + num2; num2 = num1 - num2; num2 = num1 - num2; num1 = num1 - num2; num1 = num1 - num2; System.out.println("Before Swapping"); System.out.println("Before Swapping"); System.out.println("Value of num1 is :" + num1); System.out.println("Value of num1 is :" + num1); System.out.println("Value of num2 is :" +num2); System.out.println("Value of num2 is :" +num2); } } }

Java in pictures (lection2 )22 Class Math

Java in pictures (lection2 )23 Class Math

Java in pictures (lection2 )24

Java in pictures (lection2 )25 Class Math

Java in pictures (lection2 )26 –Класс Math является конечным (final) и все методы, определённые в классе Math являются (статичными) static, т. е. невозможно наследовать от класса Math и замещать эти методы. Кроме того, класс Math имеет приватный конструктор, то есть невозможно создать его экземпляр. В классе Math есть следующие методы: ceil(), floor(), max(), min(), random(), abs(), round(), sin(), cos(), tan() и sqrt(). В классе Math есть следующие методы: ceil(), floor(), max(), min(), random(), abs(), round(), sin(), cos(), tan() и sqrt(). –Метод ceil() возвращает наименьшее значение типа double (двойной), которое не меньше аргумента и равно математическому целому. –Например: – Math.ceil(5.4) // gives 6 – Math.ceil(-6.3) // gives -6 26

Java in pictures (lection2 )27 Метод floor() возвращает наибольшее значение типа double, которое не больше, чем аргумент и равно математическому целому. Метод floor() возвращает наибольшее значение типа double, которое не больше, чем аргумент и равно математическому целому. Например: Например: Math.floor(5.4) // gives 5 Math.floor(5.4) // gives 5 Math.floor(-6.3) // gives -7 Math.floor(-6.3) // gives -7 Метод max() требует два численных аргумента и возвращает наибольший из двух. Этот метод перегружен для аргументов int, long, float или double. Метод max() требует два численных аргумента и возвращает наибольший из двух. Этот метод перегружен для аргументов int, long, float или double. Например: Например: x = Math.max(10,-10);// returns 10 x = Math.max(10,-10);// returns 10 Метод min требует два численных аргумента и возвращает наименьший из двух. Этот метод перегружен для аргументов int, long, float и double. Метод min требует два численных аргумента и возвращает наименьший из двух. Этот метод перегружен для аргументов int, long, float и double. Например: Например: x = Math.min(10,-10);// returns -10 x = Math.min(10,-10);// returns -10 Метод random() возвращает значение типа double со знаком плюс, которое больше или равно 0.0 и меньше чем 1.0. Метод random() возвращает значение типа double со знаком плюс, которое больше или равно 0.0 и меньше чем 1.0. Метод abs() возвращает абсолютное значение аргумента. Этот метод перегружен, чтобы требовать аргументы int, long, float или double. Метод abs() возвращает абсолютное значение аргумента. Этот метод перегружен, чтобы требовать аргументы int, long, float или double. Например: Например: Math.abs(-33)// returns 33 Math.abs(-33)// returns 33 27

Java in pictures (lection2 )28 Метод round() возвращает целое число, ближайшее для аргумента (перегружен для аргументов float и double ). Если число после десятичной запятой меньше, чем 0.5, Math.round() возвращает такой же результат, как Math.floor(). Во всех других случаях Math.round() работает так же, как Math.ceil(). Метод round() возвращает целое число, ближайшее для аргумента (перегружен для аргументов float и double ). Если число после десятичной запятой меньше, чем 0.5, Math.round() возвращает такой же результат, как Math.floor(). Во всех других случаях Math.round() работает так же, как Math.ceil(). Например: Например: Math.round(-1.5) // result is -1 Math.round(-1.5) // result is -1 Math.round(1.8) // result is 2 Math.round(1.8) // result is 2 Тригонометрические функции Тригонометрические функции Методы sin(), cos() и tan() возвращают соответственно синус, косинус и тангенс угла. Во всех трёх методах аргумент является углом в радианах. Значение угла, выраженное в градусах, преобразуется в значение в радианах при помощи Math.toRadians(). Методы sin(), cos() и tan() возвращают соответственно синус, косинус и тангенс угла. Во всех трёх методах аргумент является углом в радианах. Значение угла, выраженное в градусах, преобразуется в значение в радианах при помощи Math.toRadians(). Например: Например: x = Math.sin(Math.toRadians(90.0));// returns 1.0 x = Math.sin(Math.toRadians(90.0));// returns 1.0 Функция sqrt() возвращает квадратный корень аргумента типа double. Функция sqrt() возвращает квадратный корень аргумента типа double. Например: Например: x = Math.sqrt(25.0);// returns 5.0 x = Math.sqrt(25.0);// returns 5.0 Если вы передаёте отрицательное значение функции sqrt(), она возвращает NaN ("Не число"). Если вы передаёте отрицательное значение функции sqrt(), она возвращает NaN ("Не число"). 28

Java in pictures (lection2 )29 public class FindCeilingExample { public static void main(String[] args) { //Returns the same value System.out.println(Math.ceil(10)); //returns a smallest integer which is not less than 10.1, i.e. 11 System.out.println(Math.ceil(10.1)); //returns a smallest integer which is not less than 5.5, i.e. 6 System.out.println(Math.ceil(5.5)); //in this case it would be -20 System.out.println(Math.ceil(-20)); //it returns -42 not -43. (-42 is grater than 42.4 :) ) System.out.println(Math.ceil(-42.4)); //returns 0 System.out.println(Math.ceil(0)); }

Java in pictures (lection2 )30 public class FindAbsoluteValueExample { public class FindAbsoluteValueExample { public static void main(String[] args) { public static void main(String[] args) { int i = 8; int i = 8; int j = -5; int j = -5; System.out.println("Absolute value of " + i + " is :" + Math.abs(i)); System.out.println("Absolute value of " + i + " is :" + Math.abs(i)); System.out.println("Absolute value of " + j + " is :" + Math.abs(j)); System.out.println("Absolute value of " + j + " is :" + Math.abs(j)); float f1 = 10.40f; float f1 = 10.40f; float f2 = f; float f2 = f; System.out.println("Absolute value of " + f1 + " is :" + Math.abs(f1)); System.out.println("Absolute value of " + f1 + " is :" + Math.abs(f1)); System.out.println("Absolute value of " + f2 + " is :" + Math.abs(f2)); System.out.println("Absolute value of " + f2 + " is :" + Math.abs(f2)); double d1 = ; double d1 = ; double d2 = ; double d2 = ; System.out.println("Absolute value of " + d1 + " is :" + Math.abs(d1)); System.out.println("Absolute value of " + d1 + " is :" + Math.abs(d1)); System.out.println("Absolute value of " + d2 + " is :" + Math.abs(d2)); System.out.println("Absolute value of " + d2 + " is :" + Math.abs(d2)); long l1 = 34; long l1 = 34; long l2 = -439; long l2 = -439; System.out.println("Absolute value of " + l1 + " is :" + Math.abs(l1)); System.out.println("Absolute value of " + l1 + " is :" + Math.abs(l1)); System.out.println("Absolute value of " + l2 + " is :" + Math.abs(l2)); System.out.println("Absolute value of " + l2 + " is :" + Math.abs(l2)); } } }

Java in pictures (lection2 )31 public class GenerateRandomIntByRange { public class GenerateRandomIntByRange { public static void main(String args[]){ public static void main(String args[]){ /* /* The "(int)" parses the double to an int value replace 10 with The "(int)" parses the double to an int value replace 10 with your range of number. your range of number. If you want a number between 5 and 15 the range is 10 [15-5] If you want a number between 5 and 15 the range is 10 [15-5] replace the 5 with the staring number. replace the 5 with the staring number. If you want the lowest number in the range to be 5 then add 5. If you want the lowest number in the range to be 5 then add 5. Example : Example : int ran = (int)(Math.random()*100)-50; int ran = (int)(Math.random()*100)-50; will return a value in the range [-50;50] will return a value in the range [-50;50] */ */ int random = (int)(Math.random()* 10 ) + 5; int random = (int)(Math.random()* 10 ) + 5; System.out.println(random); System.out.println(random); } } }

Java in pictures (lection2 )32 import java.io.BufferedReader; import java.io.BufferedReader; import java.io.IOException; import java.io.IOException; import java.io.InputStreamReader; import java.io.InputStreamReader; public class CalculateCircleAreaExample { public class CalculateCircleAreaExample { public static void main(String[] args) { public static void main(String[] args) { int radius = 0; int radius = 0; System.out.println("Please enter radius of a circle"); System.out.println("Please enter radius of a circle"); try try { { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); radius = Integer.parseInt(br.readLine()); radius = Integer.parseInt(br.readLine()); } } catch(NumberFormatException ne) catch(NumberFormatException ne) { { System.out.println("Invalid radius value" + ne); System.out.println("Invalid radius value" + ne); System.exit(0); System.exit(0); } } catch(IOException ioe) catch(IOException ioe) { { System.out.println("IO Error :" + ioe); System.out.println("IO Error :" + ioe); System.exit(0); System.exit(0); } } double area = Math.PI * radius * radius; double area = Math.PI * radius * radius; System.out.println("Area of a circle is " + area); System.out.println("Area of a circle is " + area); } } }

Java in pictures (lection2 )33 import java.io.BufferedReader; import java.io.BufferedReader; import java.io.IOException; import java.io.IOException; import java.io.InputStreamReader; import java.io.InputStreamReader; public class CalculateCirclePerimeterExample { public class CalculateCirclePerimeterExample { public static void main(String[] args) { public static void main(String[] args) { int radius = 0; int radius = 0; System.out.println("Please enter radius of a circle"); System.out.println("Please enter radius of a circle"); try try { { //get the radius from console //get the radius from console BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); radius = Integer.parseInt(br.readLine()); radius = Integer.parseInt(br.readLine()); } } //if invalid value was entered //if invalid value was entered catch(NumberFormatException ne) catch(NumberFormatException ne) { { System.out.println("Invalid radius value" + ne); System.out.println("Invalid radius value" + ne); System.exit(0); System.exit(0); } } catch(IOException ioe) catch(IOException ioe) { { System.out.println("IO Error :" + ioe); System.out.println("IO Error :" + ioe); System.exit(0); System.exit(0); } } /* /* * Perimeter of a circle is * Perimeter of a circle is * 2 * pi * r * 2 * pi * r * where r is a radius of a circle. * where r is a radius of a circle. */ */ //NOTE : use Math.PI constant to get value of pi //NOTE : use Math.PI constant to get value of pi double perimeter = 2 * Math.PI * radius; double perimeter = 2 * Math.PI * radius; System.out.println("Perimeter of a circle is " + perimeter); System.out.println("Perimeter of a circle is " + perimeter); } } }

Java in pictures (lection2 )34 import java.io.BufferedReader; import java.io.BufferedReader; import java.io.IOException; import java.io.IOException; import java.io.InputStreamReader; import java.io.InputStreamReader; public class CalculateRectArea { public class CalculateRectArea { public static void main(String[] args) { public static void main(String[] args) { int width = 0; int width = 0; int length = 0; int length = 0; try try { { //read the length from console //read the length from console BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); System.out.println("Please enter length of a rectangle"); System.out.println("Please enter length of a rectangle"); length = Integer.parseInt(br.readLine()); length = Integer.parseInt(br.readLine()); //read the width from console //read the width from console System.out.println("Please enter width of a rectangle"); System.out.println("Please enter width of a rectangle"); width = Integer.parseInt(br.readLine()); width = Integer.parseInt(br.readLine()); } } //if invalid value was entered //if invalid value was entered catch(NumberFormatException ne) catch(NumberFormatException ne) { { System.out.println("Invalid value" + ne); System.out.println("Invalid value" + ne); System.exit(0); System.exit(0); } } catch(IOException ioe) catch(IOException ioe) { { System.out.println("IO Error :" + ioe); System.out.println("IO Error :" + ioe); System.exit(0); System.exit(0); } } /* /* * Area of a rectangle is * Area of a rectangle is * length * width * length * width */ */ int area = length * width; int area = length * width; System.out.println("Area of a rectangle is " + area); System.out.println("Area of a rectangle is " + area); } } }

Java in pictures (lection2 )35 import java.io.BufferedReader; import java.io.BufferedReader; import java.io.IOException; import java.io.IOException; import java.io.InputStreamReader; import java.io.InputStreamReader; public class CalculateRectPerimeter { public class CalculateRectPerimeter { public static void main(String[] args) { public static void main(String[] args) { int width = 0; int width = 0; int length = 0; int length = 0; try try { { //read the length from console //read the length from console BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); System.out.println("Please enter length of a rectangle"); System.out.println("Please enter length of a rectangle"); length = Integer.parseInt(br.readLine()); length = Integer.parseInt(br.readLine()); //read the width from console //read the width from console System.out.println("Please enter width of a rectangle"); System.out.println("Please enter width of a rectangle"); width = Integer.parseInt(br.readLine()); width = Integer.parseInt(br.readLine()); } } //if invalid value was entered //if invalid value was entered catch(NumberFormatException ne) catch(NumberFormatException ne) { { System.out.println("Invalid value" + ne); System.out.println("Invalid value" + ne); System.exit(0); System.exit(0); } } catch(IOException ioe) catch(IOException ioe) { { System.out.println("IO Error :" + ioe); System.out.println("IO Error :" + ioe); System.exit(0); System.exit(0); } } /* /* * Perimeter of a rectangle is * Perimeter of a rectangle is * 2 * (length + width) * 2 * (length + width) */ */ int perimeter = 2 * (length + width); int perimeter = 2 * (length + width); System.out.println("Perimeter of a rectangle is " + perimeter); System.out.println("Perimeter of a rectangle is " + perimeter); } } }

Java in pictures (lection2 )36 public class FindExponentialNumberExample { public class FindExponentialNumberExample { public static void main(String[] args) { public static void main(String[] args) { /* /* * To find exponential value of a number, use * To find exponential value of a number, use * static double exp(double d) method of Java Math class. * static double exp(double d) method of Java Math class. * * * It returns e raised to argument value. * It returns e raised to argument value. */ */ System.out.println("Exponential of 2 is : " + Math.exp(2)); System.out.println("Exponential of 2 is : " + Math.exp(2)); } } }

Java in pictures (lection2 )37 public class GenerateRandomNumbers { public class GenerateRandomNumbers { public static void main(String[] args) { public static void main(String[] args) { /* /* * To generate random numbers, use * To generate random numbers, use * static double random() method of Java Math class. * static double random() method of Java Math class. * * * This method returns a positive double value grater than 0.0 * This method returns a positive double value grater than 0.0 * and less than 1.0 * and less than 1.0 */ */ System.out.println("Random numbers between 0.0 and 1.0 are,"); System.out.println("Random numbers between 0.0 and 1.0 are,"); for(int i=0; i < 5 ; i++) for(int i=0; i < 5 ; i++) System.out.println("Random Number ["+ (i+1) + "] : " + Math.random()); System.out.println("Random Number ["+ (i+1) + "] : " + Math.random()); /* /* * To generate random number between 1 to 100 use following code * To generate random number between 1 to 100 use following code */ */ System.out.println("Random numbers between 1 and 100 are,"); System.out.println("Random numbers between 1 and 100 are,"); for(int i=0; i < 5 ; i++) for(int i=0; i < 5 ; i++) System.out.println("Random Number ["+ (i+1) + "] : " + (int)(Math.random()*100)); System.out.println("Random Number ["+ (i+1) + "] : " + (int)(Math.random()*100)); } } }

Java in pictures (lection2 )38 public class RounFloatDoubleNumbersExample { public class RounFloatDoubleNumbersExample { public static void main(String[] args) { public static void main(String[] args) { /* /* * To round float number, use * To round float number, use * static int round(float f) method of Java Math class. * static int round(float f) method of Java Math class. * * * It returns closest int number to the argument. * It returns closest int number to the argument. * Internally, it adds 0.5 to the argument, takes floor value and casts * Internally, it adds 0.5 to the argument, takes floor value and casts * the result into int. * the result into int. * * * i.e. result = (int) Math.floor( argument value + 0.5f ) * i.e. result = (int) Math.floor( argument value + 0.5f ) */ */ //returns same value //returns same value System.out.println(Math.round(10f)); System.out.println(Math.round(10f)); // returns (int) Math.floor(10.6) = 10 // returns (int) Math.floor(10.6) = 10 System.out.println(Math.round(20.5f)); System.out.println(Math.round(20.5f)); //returns (int) Math.floor( ) = 30 //returns (int) Math.floor( ) = 30 System.out.println(Math.round(20.5f)); System.out.println(Math.round(20.5f)); //returns (int) Math.floor(-18.9) = 19 //returns (int) Math.floor(-18.9) = 19 System.out.println(Math.round(-19.4f)); System.out.println(Math.round(-19.4f)); //returns (int) Math.floor(-23) = -23 //returns (int) Math.floor(-23) = -23 System.out.println(Math.round(-23.5f)); System.out.println(Math.round(-23.5f)); /* /* * To round double numbers, use * To round double numbers, use * static long round(double d) method of Java Math class. * static long round(double d) method of Java Math class. * It returns long. * It returns long. */ */ } } }

Java in pictures (lection2 )39 public class FindFloorValueExample { public class FindFloorValueExample { public static void main(String[] args) { public static void main(String[] args) { /* /* * To find a floor value, use * To find a floor value, use * static double floor(double d) method of Math class. * static double floor(double d) method of Math class. * * * It returns a largest integer which is not grater than the argument value. * It returns a largest integer which is not grater than the argument value. */ */ //Returns the same value //Returns the same value System.out.println(Math.floor(70)); System.out.println(Math.floor(70)); //returns largest integer which is not less than 30.1, i.e. 30 //returns largest integer which is not less than 30.1, i.e. 30 System.out.println(Math.floor(30.1)); System.out.println(Math.floor(30.1)); //returns largest integer which is not less than 15.5, i.e. 15 //returns largest integer which is not less than 15.5, i.e. 15 System.out.println(Math.floor(15.5)); System.out.println(Math.floor(15.5)); //in this case it would be -40 //in this case it would be -40 System.out.println(Math.floor(-40)); System.out.println(Math.floor(-40)); //it returns -43. //it returns -43. System.out.println(Math.floor(-42.4)); System.out.println(Math.floor(-42.4)); //returns 0 //returns 0 System.out.println(Math.floor(0)); System.out.println(Math.floor(0)); } } }

Java in pictures (lection2 )40 public class FindMaxOfTwoNumbersExample { public class FindMaxOfTwoNumbersExample { public static void main(String[] args) { public static void main(String[] args) { /* /* * To find maximum of two int values, use * To find maximum of two int values, use * static int max(int a, int b) method of Math class. * static int max(int a, int b) method of Math class. */ */ System.out.println(Math.max(20,40)); System.out.println(Math.max(20,40)); /* /* * To find minimum of two float values, use * To find minimum of two float values, use * static float max(float f1, float f2) method of Math class. * static float max(float f1, float f2) method of Math class. */ */ System.out.println(Math.max(324.34f, f)); System.out.println(Math.max(324.34f, f)); /* /* * To find maximum of two double values, use * To find maximum of two double values, use * static double max(double d2, double d2) method of Math class. * static double max(double d2, double d2) method of Math class. */ */ System.out.println(Math.max(65.34,123.45)); System.out.println(Math.max(65.34,123.45)); /* /* * To find maximum of two long values, use * To find maximum of two long values, use * static long max(long l1, long l2) method of Math class. * static long max(long l1, long l2) method of Math class. */ */ System.out.println(Math.max(435l,523l)); System.out.println(Math.max(435l,523l)); } } }

Java in pictures (lection2 )41 public class FindPowerExample { public class FindPowerExample { public static void main(String[] args) { public static void main(String[] args) { /* /* * To find a value raised to power of another value, use * To find a value raised to power of another value, use * static double pow(double d1, double d2) method of Java Math class. * static double pow(double d1, double d2) method of Java Math class. */ */ //returns 2 raised to 2, i.e. 4 //returns 2 raised to 2, i.e. 4 System.out.println(Math.pow(2,2)); System.out.println(Math.pow(2,2)); //returns -3 raised to 2, i.e. 9 //returns -3 raised to 2, i.e. 9 System.out.println(Math.pow(-3,2)); System.out.println(Math.pow(-3,2)); } } }

Java in pictures (lection2 )42 public class FindNaturalLogarithmOfNumberExample { public class FindNaturalLogarithmOfNumberExample { public static void main(String[] args) { public static void main(String[] args) { /* /* * To find natural logarithm value of a number, use * To find natural logarithm value of a number, use * static double log(double d) method of Java Math class. * static double log(double d) method of Java Math class. */ */ System.out.println("Natural logarithm value of 2 is : " + Math.log(2)); System.out.println("Natural logarithm value of 2 is : " + Math.log(2)); } } }

Java in pictures (lection2 )43 public class FindSquareRootExample { public class FindSquareRootExample { public static void main(String[] args) { public static void main(String[] args) { /* /* * To find square root value of a number, use * To find square root value of a number, use * static double sqrt(double d1) method Java Math class. * static double sqrt(double d1) method Java Math class. */ */ //returns square root of 9, i.e. 3 //returns square root of 9, i.e. 3 System.out.println(Math.sqrt(9)); System.out.println(Math.sqrt(9)); //returns square root of 25.5 //returns square root of 25.5 System.out.println(Math.sqrt(25.5)); System.out.println(Math.sqrt(25.5)); } } }

Java in pictures (lection2 )44

Java in pictures (lection2 )45

Java in pictures (lection2 )46 public class QuadraticEquation{ public class QuadraticEquation{ public static void main(String[] args){ public static void main(String[] args){ double a = 0.5, b = -2.7, с = 3.5, d, eps=le-8; double a = 0.5, b = -2.7, с = 3.5, d, eps=le-8; if (Math.abs(a) < eps) if (Math.abs(a) < eps) if (Math.abs(b) < eps) if (Math.abs(b) < eps) if (Math.abs(c) < eps) // Все коэффициенты равны нулю if (Math.abs(c) < eps) // Все коэффициенты равны нулю System.out.println("Решение любое число"); System.out.println("Решение любое число"); else else System.out.println("Решений нет"); System.out.println("Решений нет"); else else System.out.println("xl = x2 = " +(-c / b) ) ; System.out.println("xl = x2 = " +(-c / b) ) ; else { // Коэффициенты не равны нулю else { // Коэффициенты не равны нулю if((d = b**b 4*a*c)< 0.0){ // Комплексные корни if((d = b**b 4*a*c)< 0.0){ // Комплексные корни d = 0.5 * Math.sqrt(-d) / a; d = 0.5 * Math.sqrt(-d) / a; a = -0.5 * b/ a; a = -0.5 * b/ a; System.out.println("xl = " +a+ " +i " +d+ System.out.println("xl = " +a+ " +i " +d+ ",x2 = " +a+ " -i " +d); ",x2 = " +a+ " -i " +d); } else { } else { // Вещественные корни // Вещественные корни d =0.5 * Math.sqrt(d) / a; d =0.5 * Math.sqrt(d) / a; a = -0.5 * b / a; a = -0.5 * b / a; System.out.println("x1 = " + (a + d) + ", x2 = " +(a - d)); System.out.println("x1 = " + (a + d) + ", x2 = " +(a - d)); } } ) } Copied from: Copied from:

Java in pictures (lection2 )47 Class String

Java in pictures (lection2 )48

Java in pictures (lection2 )49

Java in pictures (lection2 )50 Class String(см. Практический курс)

Java in pictures (lection2 )51 Class StringBuffer(нет у String)

Java in pictures (lection2 )52

Java in pictures (lection2 )53 Class StringBuilder

Java in pictures (lection2 )54

Java in pictures (lection2 )55

Java in pictures (lection2 )56

Java in pictures (lection2 ) 57 Структура программ

Java in pictures (lection2 )58 Операторы Условный if()…else… выбора switch(){ case …:… default … } цикла с предусловием while(...){} цикла с постусловием do{… } while(…) параметрического цикла for(иниц ; услов ; шаг){…}

Java in pictures (lection2 )59 class PascalTriangle{ public static final int LINES = 10; public static void main(String[] args) { int[][] p, = new int [LINES] []; p[0] = new int[1]; System, out. println (p [0] [0] = 1); p[l] = new int[2]; p[l][0] = p[l][1] = 1; System.out.println(p[1][0] + " " + p[l][l]); for (int i = 2; i < LINES; i++){ p[i] = new int[i+l]; System.out.print((p[i][0] = 1) + " "); for (int j = 1; j < i; j++) System.out. print ( (p[i] [j] =p[i-l][j-l] -bp[i-l][j]) + " "); System, out. println (p [ i] [i] = 1) } Copied from:

Java in pictures (lection2 )60

Java in pictures (lection2 )61 public class FindLargestSmallestNumber { public class FindLargestSmallestNumber { public static void main(String[] args) { public static void main(String[] args) { //array of 10 numbers //array of 10 numbers int numbers[] = new int[]{32,43,53,54,32,65,63,98,43,23}; int numbers[] = new int[]{32,43,53,54,32,65,63,98,43,23}; //assign first element of an array to largest and smallest //assign first element of an array to largest and smallest int smallest = numbers[0]; int smallest = numbers[0]; int largetst = numbers[0]; int largetst = numbers[0]; for(int i=1; i< numbers.length; i++) for(int i=1; i< numbers.length; i++) { { if(numbers[i] > largetst) if(numbers[i] > largetst) largetst = numbers[i]; largetst = numbers[i]; else if (numbers[i] < smallest) else if (numbers[i] < smallest) smallest = numbers[i]; smallest = numbers[i]; } } System.out.println("Largest Number is : " + largetst); System.out.println("Largest Number is : " + largetst); System.out.println("Smallest Number is : " + smallest); System.out.println("Smallest Number is : " + smallest); } } }

Java in pictures (lection2 )62 public class FindLargestSmallestNumber { public class FindLargestSmallestNumber { public static void main(String[] args) { public static void main(String[] args) { //array of 10 numbers //array of 10 numbers int numbers[] = new int[]{32,43,53,54,32,65,63,98,43,23}; int numbers[] = new int[]{32,43,53,54,32,65,63,98,43,23}; //assign first element of an array to largest and smallest //assign first element of an array to largest and smallest int smallest = numbers[0]; int smallest = numbers[0]; int largetst = numbers[0]; int largetst = numbers[0]; for(int i=1; i< numbers.length; i++) for(int i=1; i< numbers.length; i++) { { if(numbers[i] > largetst) if(numbers[i] > largetst) largetst = numbers[i]; largetst = numbers[i]; else if (numbers[i] < smallest) else if (numbers[i] < smallest) smallest = numbers[i]; smallest = numbers[i]; } } System.out.println("Largest Number is : " + largetst); System.out.println("Largest Number is : " + largetst); System.out.println("Smallest Number is : " + smallest); System.out.println("Smallest Number is : " + smallest); } } }

Java in pictures (lection2 )63 public class FindEvenOrOddNumber { public class FindEvenOrOddNumber { public static void main(String[] args) { public static void main(String[] args) { //create an array of 10 numbers //create an array of 10 numbers int[] numbers = new int[]{1,2,3,4,5,6,7,8,9,10}; int[] numbers = new int[]{1,2,3,4,5,6,7,8,9,10}; for(int i=0; i < numbers.length; i++){ for(int i=0; i < numbers.length; i++){ /* /* * use modulus operator to check if the number is even or odd. * use modulus operator to check if the number is even or odd. * If we divide any number by 2 and reminder is 0 then the number is * If we divide any number by 2 and reminder is 0 then the number is * even, otherwise it is odd. * even, otherwise it is odd. */ */ if(numbers[i]%2 == 0) if(numbers[i]%2 == 0) System.out.println(numbers[i] + " is even number."); System.out.println(numbers[i] + " is even number."); else else System.out.println(numbers[i] + " is odd number."); System.out.println(numbers[i] + " is odd number."); } } } } }

Java in pictures (lection2 )64 public class FindLargestSmallestNumber { public class FindLargestSmallestNumber { public static void main(String[] args) { public static void main(String[] args) { //array of 10 numbers //array of 10 numbers int numbers[] = new int[]{32,43,53,54,32,65,63,98,43,23}; int numbers[] = new int[]{32,43,53,54,32,65,63,98,43,23}; //assign first element of an array to largest and smallest //assign first element of an array to largest and smallest int smallest = numbers[0]; int smallest = numbers[0]; int largetst = numbers[0]; int largetst = numbers[0]; for(int i=1; i< numbers.length; i++) for(int i=1; i< numbers.length; i++) { { if(numbers[i] > largetst) if(numbers[i] > largetst) largetst = numbers[i]; largetst = numbers[i]; else if (numbers[i] < smallest) else if (numbers[i] < smallest) smallest = numbers[i]; smallest = numbers[i]; } } System.out.println("Largest Number is : " + largetst); System.out.println("Largest Number is : " + largetst); System.out.println("Smallest Number is : " + smallest); System.out.println("Smallest Number is : " + smallest); } } }

Java in pictures (lection2 )65 public class NumberFactorial { public class NumberFactorial { public static void main(String[] args) { public static void main(String[] args) { int number = 5; int number = 5; /* /* * Factorial of any number is !n. * Factorial of any number is !n. * For example, factorial of 4 is 4*3*2*1. * For example, factorial of 4 is 4*3*2*1. */ */ int factorial = number; int factorial = number; for(int i =(number - 1); i > 1; i--) for(int i =(number - 1); i > 1; i--) { { factorial = factorial * i; factorial = factorial * i; } } System.out.println("Factorial of a number is " + factorial); System.out.println("Factorial of a number is " + factorial); } } }

Java in pictures (lection2 )66 import java.io.BufferedReader; import java.io.BufferedReader; import java.io.IOException; import java.io.IOException; import java.io.InputStreamReader; import java.io.InputStreamReader; public class JavaFactorialUsingRecursion { public class JavaFactorialUsingRecursion { public static void main(String args[]) throws NumberFormatException, IOException{ public static void main(String args[]) throws NumberFormatException, IOException{ System.out.println("Enter the number: "); System.out.println("Enter the number: "); //get input from the user //get input from the user BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); int a = Integer.parseInt(br.readLine()); int a = Integer.parseInt(br.readLine()); //call the recursive function to generate factorial //call the recursive function to generate factorial int result= fact(a); int result= fact(a); System.out.println("Factorial of the number is: " + result); System.out.println("Factorial of the number is: " + result); } } static int fact(int b) static int fact(int b) { { if(b

Java in pictures (lection2 )67 public class ReverseNumber { public class ReverseNumber { public static void main(String[] args) { public static void main(String[] args) { //original number //original number int number = 1234; int number = 1234; int reversedNumber = 0; int reversedNumber = 0; int temp = 0; int temp = 0; while(number > 0){ while(number > 0){ //use modulus operator to strip off the last digit //use modulus operator to strip off the last digit temp = number%10; temp = number%10; //create the reversed number //create the reversed number reversedNumber = reversedNumber * 10 + temp; reversedNumber = reversedNumber * 10 + temp; number = number/10; number = number/10; } } //output the reversed number //output the reversed number System.out.println("Reversed Number is: " + reversedNumber); System.out.println("Reversed Number is: " + reversedNumber); } } }

Java in pictures (lection2 )68 Пакет java.io.*; import java.io.*;// потоки ввода-вывода import java.io.*;// потоки ввода-вывода

Java in pictures (lection2 )69 package java.io;

Java in pictures (lection2 )70

Java in pictures (lection2 )71

Java in pictures (lection2 )72

Java in pictures (lection2 )73

Java in pictures (lection2 )74

Java in pictures (lection2 )75