Computer Programming, I. Laboratory Manual. Experiment #4. Mathematical Functions & Characters

Similar documents
CS-201 Introduction to Programming with Java

Chapter 2 ELEMENTARY PROGRAMMING

Module 4: Characters, Strings, and Mathematical Functions

Computer Programming, I. Laboratory Manual. Experiment #6. Loops

Chapter 4 Mathematical Functions, Characters, and Strings

Computer Programming, I. Laboratory Manual. Experiment #2. Elementary Programming

Chapter 2 Elementary Programming

Programming with Java

Computer Programming, I. Laboratory Manual. Experiment #7. Methods

CS5000: Foundations of Programming. Mingon Kang, PhD Computer Science, Kennesaw State University

Chapter 4. Mathematical Functions, Characters, and Strings. Program Listings

Chapter 3 Selections. Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved.

Chapter 2 Primitive Data Types and Operations

Eng. Mohammed Abdualal

Computer Programming, I. Laboratory Manual. Experiment #5. Strings & Text Files Input

Computer Programming, I. Laboratory Manual. Experiment #3. Selections

Chapter 2 Primitive Data Types and Operations. Objectives

Basic computer skills such as using Windows, Internet Explorer, and Microsoft Word. Chapter 1 Introduction to Computers, Programs, and Java

Computational Expression

Chapter 2 Primitive Data Types and Operations

Entry Point of Execution: the main Method. Elementary Programming. Compile Time vs. Run Time. Learning Outcomes

Elementary Programming

Zheng-Liang Lu Java Programming 45 / 79

Elementary Programming. CSE 114, Computer Science 1 Stony Brook University

Tester vs. Controller. Elementary Programming. Learning Outcomes. Compile Time vs. Run Time

CHAPTER 4 MATHEMATICAL FUNCTIONS, CHARACTERS, STRINGS

JAVA Programming Concepts

Entry Point of Execution: the main Method. Elementary Programming. Learning Outcomes. Development Process

Lecture Notes. System.out.println( Circle radius: + radius + area: + area); radius radius area area value

Motivations 9/14/2010. Introducing Programming with an Example. Chapter 2 Elementary Programming. Objectives

Chapter 2 Elementary Programming

Chapter 2 Using Data. Instructor s Manual Table of Contents. At a Glance. Overview. Objectives. Teaching Tips. Quick Quizzes. Class Discussion Topics

Mathematical Functions, Characters, and Strings. CSE 114, Computer Science 1 Stony Brook University

Full file at

Important Java terminology

CS1150 Principles of Computer Science Math Functions, Characters and Strings (Part II)

Full file at

CEN 414 Java Programming

Visual C# Instructor s Manual Table of Contents

COMP Primitive and Class Types. Yi Hong May 14, 2015

Mathematical Functions, Characters, and Strings. CSE 114, Computer Science 1 Stony Brook University

CSCI 2010 Principles of Computer Science. Data and Expressions 08/09/2013 CSCI

char ch = astring; //where astring is a String..illegal char ch = A ; //illegal

Introduction to Computers. Laboratory Manual. Experiment #3. Elementary Programming, II

Java Notes. 10th ICSE. Saravanan Ganesh

Computer Programming, I. Laboratory Manual. Final Exam Solution

Java Foundations: Introduction to Program Design & Data Structures, 4e John Lewis, Peter DePasquale, Joseph Chase Test Bank: Chapter 2

Eng. Mohammed S. Abdualal

A variable is a name for a location in memory A variable must be declared

Getting started with Java

Chapter 3. Selections. Program Listings

Reserved Words and Identifiers

Chapter 4 Mathematical Functions, Characters, and Strings

Primitive Data Types: Intro

Chapter 3 Selections. 3.1 Introduction. 3.2 boolean Data Type

Date: Dr. Essam Halim

Data and Expressions. Outline. Data and Expressions 12/18/2010. Let's explore some other fundamental programming concepts. Chapter 2 focuses on:

false, import, new 1 class Lecture2 { 2 3 "Data types, Variables, and Operators" 4

Using Java Classes Fall 2018 Margaret Reid-Miller

Basic data types. Building blocks of computation

MATHEMATICAL FUNCTIONS CHARACTERS, AND STRINGS. INTRODUCTION IB DP Computer science Standard Level ICS3U

JAVA PROGRAMMING LAB. ABSTRACT In this Lab you will learn to write programs for executing statements repeatedly using a while, do while and for loop

Chapter 2: Data and Expressions

Chapter 2: Data and Expressions

AP Computer Science A

Chapter 2 Using Data. Instructor s Manual Table of Contents. At a Glance. A Guide to this Instructor s Manual:

Peer Instruction 1. Elementary Programming

Object-Oriented Programming

Chapter 02: Using Data

Chapter 2: Data and Expressions

Chapter 2. Elementary Programming

Review for Test 1 (Chapter 1-5)

Assoc. Prof. Dr. Marenglen Biba. (C) 2010 Pearson Education, Inc. All rights reserved.

Chapter 6 Primitive types

What did we talk about last time? Examples switch statements

boolean, char, class, const, double, else, final, float, for, if, import, int, long, new, public, return, static, throws, void, while

Chapter 2: Using Data

Data Types. 1 You cannot change the type of the variable after declaration. Zheng-Liang Lu Java Programming 52 / 87

Data and Variables. Data Types Expressions. String Concatenation Variables Declaration Assignment Shorthand operators. Operators Precedence

12/22/11. Java How to Program, 9/e. Help you get started with Eclipse and NetBeans integrated development environments.

Java Classes: Math, Integer A C S L E C T U R E 8

JAVA Programming Fundamentals

CONTENTS: Compilation Data and Expressions COMP 202. More on Chapter 2

CS313D: ADVANCED PROGRAMMING LANGUAGE

Computer Programming, I. Laboratory Manual. Experiment #9. Multi-Dimensional Arrays

Java Programming Fundamentals. Visit for more.


Features of C. Portable Procedural / Modular Structured Language Statically typed Middle level language

Chapter 3: Operators, Expressions and Type Conversion

Basic Operations jgrasp debugger Writing Programs & Checkstyle

Section 2.2 Your First Program in Java: Printing a Line of Text

2: Basics of Java Programming

C How to Program, 6/e by Pearson Education, Inc. All Rights Reserved.

Basic Computation. Chapter 2

Objectives. Chapter 2: Basic Elements of C++ Introduction. Objectives (cont d.) A C++ Program (cont d.) A C++ Program

Chapter 2: Basic Elements of C++

Chapter 2: Basic Elements of C++ Objectives. Objectives (cont d.) A C++ Program. Introduction

1 class Lecture2 { 2 3 "Elementray Programming" / References 8 [1] Ch. 2 in YDL 9 [2] Ch. 2 and 3 in Sharan 10 [3] Ch.

Methods CSC 121 Fall 2016 Howard Rosenthal

COMP-202 Unit 2: Java Basics. CONTENTS: Using Expressions and Variables Types Strings

Transcription:

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