Think Twice Code Once The Islamic University of Gaza Engineering Faculty Department of Computer Engineering Fall 2017 ECOM 2005 Khaleel I. Shaheen Computer Programming, I Laboratory Manual Experiment #4 Mathematical Functions & Characters
Mathematical Functions Java provides many useful methods in the Math class for performing common mathematical functions. A method is a group of statements that performs a specific task. We have already used methods like println() and nextint(). This lab introduces other useful methods in the Math class. They can be categorized as trigonometric methods, exponent methods, and service methods. Trigonometric Methods The Math class contains the following methods for performing trigonometric functions. Note that the parameters for sin, cos, and tan is an angle in radians. Exponent Methods Exponent methods in the Math class are shown below. 2
Rounding Methods The Math class contains five rounding methods as shown. Other mathematical functions min and max methods return the minimum and maximum numbers of two numbers. abs method returns the absolute value of the number. random method generates a random double value greater than or equal to 0.0 and less than 1.0. // Returns a random number between a and a + b, excluding a + b a + Math.random() * b For example, to generate a random number in the period [5,15]: (int)(5 + Math.random() * 11) Ex: Write a program that randomly generates a number of two digits, prompts the user to enter a two-digit number, and determines whether the user wins according to the following rules: 1. If the user input matches the lottery number in the exact order, the award is $10,000. 2. If all digits in the user input match all digits in the lottery number, the award is $3,000. 3. If one digit in the user input matches a digit in the lottery number, the award is $1,000. 3
Scanner input = new Scanner(System.in); int lottery = (int) (Math.random() * 100); System.out.print("Enter your lottery pick (two digits): "); int guess = input.nextint(); int lotterydigit1 = lottery / 10; int lotterydigit2 = lottery % 10; int guessdigit1 = guess / 10; int guessdigit2 = guess % 10; System.out.println("The lottery number is " + lottery); if (guess == lottery) System.out.println("Exact match: you win $10,000"); else if (guessdigit2 == lotterydigit1 && guessdigit1 == lotterydigit2) System.out.println("Match all digits: you win $3,000"); else if (guessdigit1 == lotterydigit1 guessdigit1 == lotterydigit2 guessdigit2 == lotterydigit1 guessdigit2 == lotterydigit2) System.out.println("Match one digit: you win $1,000"); else System.out.println("Sorry, no match"); Character Data Type and Operations The character data type, char, is used to represent a single character. A character literal is enclosed in single quotation marks. char letter = 'A'; char numchar = '4'; A string literal must be enclosed in double quotation marks (" "). A character literal is a single character enclosed in single quotation marks (' '). Therefore, "A" is a string, but 'A' is a character. 4
Encoding scheme Computers use binary numbers internally. A character is stored in a computer as a sequence of 0s and 1s. Mapping a character to its binary representation is called encoding. There are different ways to encode a character. How characters are encoded is defined by an encoding scheme. Most computers use ASCII, an 8-bit encoding scheme for representing all uppercase and lowercase letters, digits, punctuation marks, and control characters. Java supports Unicode, an encoding scheme established to support the interchange, processing, and display of written texts in the world s diverse languages. Unicode was designed as a 16-bit character encoding. The primitive data type char was intended to take advantage of this design by providing a simple data type that could hold any character. A 16-bit Unicode takes two bytes, preceded by \u, expressed in four hexadecimal digits that run from \u0000 to \uffff. Unicode includes ASCII code, with \u0000 to \u007f corresponding to the 128 ASCII characters. You can use ASCII characters such as 'X', '1', and '$' in a Java program as well as Unicode. Thus, for example, the following statements are equivalent: char letter = 'A'; char letter = '\u0041'; // Character A's Unicode is 0041 Both statements assign character A to the char variable letter. The following table representing Unicode values for commonly used characters: The increment and decrement operators can also be used on char variables to get the next or preceding Unicode character. For example, the following statements display character C. 5
char ch = 'B'; System.out.println(++ch); Escape Sequences In Java, can we write a statement like the one below? System.out.println("He said "Java is fun""); No, we can't. This statement has syntax errors, as the second quotation terminates the string, and the compiler don t know what to do with the rest of the statement. Java uses a special notation to represent special characters. This special notation, called an escape sequence, consists of a backslash (\) followed by a character or a combination of digits. So now we can rewrite the previous statement using escape sequence. System.out.println("He said \"Java is fun\""); Note that the symbols \ and " together represent one character. Ex: Write ONE Java Statement to print to following lines to the Console: Welcome to "IUG\JavaLab" Lab4: Math Functions & Characters. 6
System.out.println("Welcome to \"IUG\\JavaLab\"\nLab4:\tMath Functions & Characters."); Casting between char and Numeric Types A char can be cast into any numeric type, and vice versa. char ch = (char)0x0041; // ch is character A When a floating-point value is cast into a char, the floating-point value is first cast into an int, which is then cast into a char. char ch = (char)65.25; // ch is character A When a char is cast into a numeric type, the character s Unicode is cast into the specified numeric type. int i = (int)'a'; // i is 65 Implicit casting can be used if the result of a casting fits into the target variable. Otherwise, explicit casting must be used. For example, since the Unicode of 'a' is 97, which is within the range of a byte, these implicit castings are fine: byte b = 'a'; int i = 'a'; But the following casting is incorrect, because the Unicode \ufff4 cannot fit into a byte: byte b = '\ufff4'; To force this assignment, use explicit casting, as follows: byte b = (byte) '\ufff4'; Ex: Write a program that prints the Unicode for '9' and '$'. 7
char ninech = '9'; char dollarch = '$'; System.out.println((int) ninech); // prints 57 System.out.println((int) dollarch); // prints 36 Note that all numeric operators can be applied to char operands. A char operand is automatically cast into a number if the other operand is a number or a character. If the other operand is a string, the character is concatenated with the string. For example, the following statements: int i = '2' + '3'; // (int)'2' is 50 and (int)'3' is 51 System.out.println("i is " + i); // i is 101 int j = 2 + 'a'; // (int)'a' is 97 System.out.println("j is " + j); // j is 99 System.out.println(j + " is the Unicode for character " + (char)j); // 99 is the Unicode for character c System.out.println("Lab " + '4'); Comparing and Testing Characters Two characters can be compared using the relational operators just like comparing two numbers. This is done by comparing the Unicode of the two characters. For example, /* true because the Unicode for 'a' (97) is less than the Unicode for 'b' (98). */ System.out.println('a' < 'b'); /* false because the Unicode for 'a' (97) is greater than the Unicode for 'A' (65). */ System.out.println('a' < 'A'); Ex: Write a program that reads a character and prints weather it's a capital letter, small letter or a digit. 8
char ch = 'A'; if (ch >= 'A' && ch <= 'Z') System.out.println(ch + " is an uppercase letter"); else if (ch >= 'a' && ch <= 'z') System.out.println(ch + " is a lowercase letter"); else if (ch >= '0' && ch <= '9') System.out.println(ch + " is a numeric character"); Java provides the following methods in the Character class for testing characters. Ex: Re-Write the previous exercise using the built-in Java methods. char ch = 'A'; if (Character.isUpperCase(ch)) System.out.println(ch + " is an uppercase letter"); else if (Character.isLowerCase(ch)) System.out.println(ch + " is a lowercase letter"); else if (Character.isDigit(ch)) System.out.println(ch + " is a numeric character"); Lab Work Ex1: A regular polygon is an n-sided polygon in which all sides are of the same length and all angles have the same degree. The formula for computing the area of a regular polygon is n s 2 Area = 4 tan ( π n ) 9
s is the length of a side. Write a program that prompts the user to enter the number of sides and their length of a regular polygon and displays its area. Scanner input = new Scanner(System.in); System.out.print("Enter the number of sides: "); int numberofsides = input.nextint(); System.out.print("Enter the side: "); double side = input.nextdouble(); double area = numberofsides * Math.pow(side, 2) / (Math.tan(Math.PI / numberofsides) * 4); System.out.println("The area of the polygon is " + area); Ex2: Write a program that prompts the user to enter a character ch. If the character is 'U' or 'u' then generate a random uppercase letter. If the character is 'L' or 'l' then generate a random lowercase letter. Else, print the character. Scanner input = new Scanner(System.in); System.out.print("Enter a character: "); char c = input.next().charat(0); char random; if (c == 'U' c == 'u') { random = (char) ('A' + Math.random() * ('Z' - 'A' + 1)); System.out.println("Randomly generated uppercase letter is: \"" + random + "\""); } else if (c == 'L' c == 'l') { random = (char) ('a' + Math.random() * ('z' - 'a' + 1)); System.out.println("Randomly generated lowercase letter is: \"" + random + "\""); } else { System.out.println("Your character\\ \"" + c + "\""); } 10
Ex3: Write a program that receives an ASCII code (an integer between 0 and 127) and displays its character. Scanner input = new Scanner(System.in); System.out.print("Enter an ASCII code: "); int code = input.nextint(); System.out.println("The character for ASCII code " + code + " is " + (char)code); Homework 1. Write a program that reads three numbers and prints the maximum number. (Use Math class). 2. Write statements that assign random integers to the variable n in the following ranges: a) 1 n 2. b) 1 n 100. c) 0 n 9. d) 1000 n 1112. e) 1 n 1. f) 3 n 11. 3. Write a program that prints the following characters to the console \ and "? 4. Write a program that prompts the user to enter a single character. Print whether the character Vowel or Consonant, depending on the user input. 5. Write a program that receives a character and displays its Unicode. Good Luck 11