Lecture 5 (Chapter 2)
Lecture 5 (Chapter 2)
Lecture 5
Chapter 2:
Introduction to Java Programming
2
Scanner methods
Method Description
nextInt() reads an int from the user
nextDouble() reads a double from the user
nextFloat() reads a float from the user
next() reads a one-word String from the user
next().charAt(0) reads one char from the user
• Each method waits until the user presses Enter.
• The value typed by the user is returned.
Example:
System.out.print("How old are you? ");
int age = input.nextInt();
System.out.println("You typed " + age);
Scanner Example
import java.util.Scanner; // so that I can use Scanner
years 36
int years = 65 - age;
System.out.println(years + " years to
retirement!");
}
}
Output:
5
Example: A Program to calculate the area of rectangle.
Output:
6
Example: A Program to calculate the net salary
7
Java's Math class
Method name Description
Math.abs(value) absolute value
Math.ceil(value) rounds up
Math.floor(value) rounds down
Math.log10(value) logarithm, base 10
Math.max(value1, value2) larger of two values
Math.min(value1, value2) smaller of two values
Math.pow(base, exp) base to the exp power
Math.random() random double between 0 and 1
Math.round(value) nearest whole number
Math.sqrt(value) square root
Math.sin(value) sine/cosine/tangent of
Math.cos(value) an angle in radians Constant Description
Math.tan(value) Math.E 2.7182818...
Math.toDegrees(value) convert degrees to Math.PI 3.1415926...
Math.toRadians(value) radians and back
Calling Math methods
Math.methodName(parameters)
Examples:
double squareRoot = Math.sqrt(121.0);
System.out.println(squareRoot); // 11.0
System.out.println(Math.min(3, 7) + 2); // 5
10
Remember: Type casting
• type cast: A conversion from one type to another.
• To promote an int into a double to get exact division from /
• To truncate a double from a real number to an integer
• Syntax:
(type) expression
Examples:
double result = (double) 19 / 5; // 3.8
int result2 = (int) result; // 3
int x = (int) Math.pow(10, 3); // 1000
Calling Math methods
• Parameters send information in from the caller to the method.
• Return values send information out from a method to its caller.
• A call to the method can be used as part of an expression.
-42 Math.abs(-42)
42
main
2.71
3
Math.round(2.71)
Example:
Java program to find the Hypotenuse of a right-angled triangle
13