Issuu on Google+

JAVA 02 Dr. Muditha Hapudeniya MBBS, MSc, AMBCS


Out Line ● ● ● ● ● ● ●

Recap of previous lecture If then , if then else Switch While Do while For Break, continue, return


Data Types


Defining and using variable Define by the data type followed by the variable name:

int numberOfDays;

short hour;

float reactionTime; Initialized before use

– –

int numberOfDays; numberOfDays = 7;


Exercise â—?

Write a java program to calculate the BMI for given weight and height.


Exercise Write a java program to calculate the following for given radius ( r ) of a circle.

– – – –

Diameter - 2r Circumference – 2πr Area – πr2 Volume – 4/3 πr3 ●

π = 3.1416


Math functions in Java ●

Lots of mathematical functions are built-in to the Java lang.

Math class in java.lang package provides these functions.

There is no need to import

Some useful functions are –

PI

abs(), ceil(), floor(), round()

max(), min()

pow()

random()

sqrt()

Example


The if-then-else Statement


The if-then-else Statement The syntax for IF-ELSE statement is if(expression) { // IF statement block : TRUE } else // optional { // ELSE statement block : FALSE }

if (value % 2 == 1) { result = "Number is Odd"; } else { result = "Number is Even"; }

Example


The switch Statement â—?

Long list of nested IF can be replaced by switch statement Int x= 90; switch (x) { case 100: System.out.println("100"); break; case 90: System.out.println("90"); break; default: System.out.println("not found"); break; } What is the function of break ?

Example


Exercise â—?

Modify the java program written for calculate the BMI to categorise

Category Severely underweight Underweight Normal Overweight Obese Class I Obese Class II Obese Class III

BMI range – kg/m2 less than 16.0 from 16.1 to 18.5 from 18.6 to 25 from 26 to 30 from 31 to 35 from 36 to 40 over 41


while Statements â—?

The while statement continually executes a block of statements while a particular condition is true while (expression) { statement(s) } int count = 1; while (count < 11) { System.out.println("Count is: " + count); count++; }


do - while Statements â&#x2014;?

Similar to while but the statements within the do block are always executed at least once do { statement(s) } while (expression);

int count = 1; do { System.out.println("Count is: " + count); count++; } while (count <= 11); Example


for Statement â&#x2014;?

for statement provides a compact way to iterate over a range of values for (initialization; termination; increment) { statement(s) } for(int i=1; i<11; i++){ System.out.println("Count is: " + i); }


while Statements â&#x2014;?

The while statement continually executes a block of statements while a particular condition is true while (expression) { statement(s) } int count = 1; while (count < 11) { System.out.println("Count is: " + count); count++; }


Branching Statements break Statement terminate a for, while, or do-while loop continue Statement skips the current iteration of a for, while , or dowhile loop return Statement exits from the current method, and control flow returns to where the method was invoked Example


Practise


Java arrays â&#x2014;?

An array is a container object that holds a fixed number of values of a single type. The length of an array is established when the array is created. After creation, its length is fixed


Declaring, Creating, Initialising, and Accessing an Array Type[] varName; int[] anArray; // declares an array of integers anArray = new int[10]; // create an array of integers anArray[0] = 100; // initialize first element anArray[1] = 200; // initialize second element anArray[2] = 300; // etc. // another way int[] anArray = {100, 200, 300, 400, 500, 600, 700, 800, 900, 1000}; // accessing a array System.out.println("Element 1 at index 0: " + anArray[0]);

Example


Multidimensional array You can also declare an array of arrays (also known as a multidimensional array) by using two or more sets of square brackets Each element, therefore, must be accessed by a corresponding number of index values. a multidimensional array is simply an array whose components are themselves arrays. String[][] names = {{"Mr. ", "Mrs. ", "Ms. "}, {"Smith", "Jones"}}; Int [][] multyArray = new int[5][5]; MultiArray[0][0]=12;


Multidimensional array int[ ][ ] aryNumbers = new int[6][5]; aryNumbers[0][0] = 10; aryNumbers[0][1] = 12; aryNumbers[0][2] = 43; aryNumbers[0][3] = 11; aryNumbers[0][4] = 22;

0

1

2

aryNumbers[1][0] = 20; aryNumbers[1][1] = 45; aryNumbers[1][2] = 56; aryNumbers[1][3] = 1; aryNumbers[1][4] = 33;

[row, column] Example

3

4


String Manipulation Useful string handling methods i = s.length()

length of the string s.

b = s.equals(t)

true if the two strings have equal values

b = s.equalsIgnoreCase(t) same as above ignoring case c = s.charAt(i)

char at position i in s.

s1 =

s.substring(i) substring from index i to the end of s.

s1 =

s.substring(i, j)

s1 =

s.toLowerCase() new String with all chars lowercase

s1 =

s.toUpperCase() new String with all chars uppercase

s1 =

s.trim() new String with whitespace deleted from front and back

s1 =

s.replace(c1, c2) new String with all c1 characters replaced by character c2.

s1 =

s.replace(cs2, cs3)

substring from index i to BEFORE index j of s.

new String with all cs2 substrings replaced by cs3.


String to Number conversion Frequently, a program ends up with numeric data in a string objectâ&#x20AC;&#x201D;a value entered by the user, for example. The Number subclasses that wrap primitive numeric types ( Byte, Integer, Double, Float, Long, and Short) each provide a class method named valueOf that converts a string to an object of that type. String s = 10; byte b = Byte.valueOf(s); Int I = Integer.valueOf(s); //The valueOf class method. Int I = Integer.parseInt(s); //The parseInt class method.

Example


Number to String conversion Sometimes you need to convert a number to a string because you need to operate on the value in its string form. There are several easy ways to convert a number to a string: int I = 10 ; String s1 = "" + i; //Concatenate "i" with an empty string; String s2 = String.valueOf(i); //The valueOf class method. toString(), that will convert its primitive type to a string int i; double d; String s3 = Integer.toString(i); //The toString class method. String s4 = Double.toString(d); //The toString class method. Example


Getting User input Method 1 You can provide values when you start the java program as command line arguments. They are stored in the main method array. public class UserInput1 { public static void main(String[] args) { String s1=args[0]; String s2=args[1]; System.out.println(s1); System.out.println(s2); }} $> java UserInput1 1234 abcd

Example


Getting User input Method 2 For interactive user inputs you can use Scanner class in java.util package. import java.util.Scanner; // import the Scanner class public class UserInput2 { public static void main(String[] args) { Scanner scan = new Scanner(System.in); // create Scanner object String usrInput; // variable to hold the user input System.out.print("Enter the input : "); // prompt usrInput = scan.next(); // read the user input as a string System.out.println(usrInput); // print the user input }}

Example


Do more java exercises


Exercises

● ●

● ●

Convert the BMI calculation program to useful interactive program Convert a full name in to a name with initials Get 10 numbers from the user and give mean, mode, min, max, SD


Java lecture