CS 201 California State University, Los Angeles.  Various Mathematical Functions  Characters  Strings.

Slides:



Advertisements
Similar presentations
Escape Sequences \n newline \t tab \b backspace \r carriage return
Advertisements

Primitive Data Types There are a number of common objects we encounter and are treated specially by almost any programming language These are called basic.
Constants and Data Types Constants Data Types Reading for this class: L&L,
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All rights reserved. 1 Chapter 4 Mathematical Functions, Characters,
1 Fundamental Data types Overview l Primitive Data Types l Variable declaration l Arithmetical Operations l Expressions l Assignment statement l Increment.
©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter 9: Characters * Character primitives * Character Wrapper class.
1 Chapter 3 Arithmetic Expressions. 2 Chapter 3 Topics l Overview of Java Data Types l Numeric Data Types l Declarations for Numeric Expressions l Simple.
COMPSCI 125 Spring 2005 ©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter 3: Numeric Data *Variables *Numeric data.
More on Numerical Computation CS-2301 B-term More on Numerical Computation CS-2301, System Programming for Non-majors (Slides include materials from.
ECE122 L3: Expression Evaluation February 6, 2007 ECE 122 Engineering Problem Solving with Java Lecture 3 Expression Evaluation and Program Interaction.
CS180 Recitation 3. Lecture: Overflow byte b; b = 127; b += 1; System.out.println("b is" + b); b is -128 byte b; b = 128; //will not compile! b went out.
The UNIVERSITY of NORTH CAROLINA at CHAPEL HILL Adrian Ilie COMP 14 Introduction to Programming Adrian Ilie June 27, 2005.
Primitive Types Java supports two kinds of types of values – objects, and – values of primitive data types variables store – either references to objects.
1 Data types, operations, and expressions Continued l Overview l Assignment statement l Increment and Decrement operators l Short hand operators l The.
String Escape Sequences
1 Chapter 2 JAVA FUNDAMENTALS CONT’D. 2 PRIMITIVE DATA TYPES Computer programs operate on data values. Values in Java are classified according to their.
Lesson 3 – Regular Expressions Sandeepa Harshanganie Kannangara MBCS | B.Sc. (special) in MIT.
EG280 - CS for Engineers Chapter 2, Introduction to C Part I Topics: Program structure Constants and variables Assignment Statements Standard input and.
Input & Output: Console
Week 3 - Wednesday.  What did we talk about last time?  Math methods  Lab 2.
© Copyright 2013 by Pearson Education, Inc. All Rights Reserved.1 Chapter 4 Mathematical Functions, Characters, and Strings.
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All rights reserved. 1 Chapter 4 Mathematical Functions, Characters,
Outline Questions / Review Predefined Objects Variables Primitive Data Arithmetic Expressions Interactive Programs Decision Making Assignments.
1 Do you have a CS account? Primitive types –“ building blocks ” for more complicated types Java is strongly typed –All variables in a Java program must.
Introduction to Java Applications Part II. In this chapter you will learn:  Different data types( Primitive data types).  How to declare variables?
CIS 260: App Dev I. 2 Programs and Programming n Program  A sequence of steps designed to accomplish a task n Program design  A detailed _____ for implementing.
Chapter 2: Using Data.
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All rights reserved. 1 Chapter 4 Mathematical Functions, Characters,
CIS 260: App Dev I. 2 Programs and Programming n Program  A sequence of steps designed to accomplish a task n Program design  A detailed _____ for implementing.
An Introduction to Java Programming and Object-Oriented Application Development Chapter 7 Characters, Strings, and Formatting.
Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved. int: integers, no fractional part: 1, -4, 0 double : floating-point.
CHAPTER 4 GC 101 Data types. DATA TYPES  For all data, assign a name (identifier) and a data type  Data type tells compiler:  How much memory to allocate.
Java Overview. Comments in a Java Program Comments can be single line comments like C++ Example: //This is a Java Comment Comments can be spread over.
Copyright Curt Hill Variables What are they? Why do we need them?
© Copyright 2012 by Pearson Education, Inc. All Rights Reserved. 1 Chapter 3 Mathematical Functions, Strings, and Objects.
Java Programming, Second Edition Chapter Two Using Data Within a Program.
A Simple Java Program //This program prints Welcome to Java! public class Welcome { public static void main(String[] args) { public static void main(String[]
Programming Fundamentals. Summary of previous lectures Programming Language Phases of C++ Environment Variables and Data Types.
CSM-Java Programming-I Spring,2005 Fundamental Data Types Lesson - 2.
COMP 110: Spring Announcements Lab 1 due Wednesday at Noon Assignment 1 available on website Online drop date is today.
A data type in a programming language is a set of data with values having predefined characteristics.data The language usually specifies:  the range.
Chapter 2: Data and Expressions. Variable Declaration In Java when you declare a variable, you must also declare the type of information it will hold.
Lecture 5: java.lang.Math, java.lang.String and Characters Michael Hsu CSULA.
CS0007: Introduction to Computer Programming Primitive Data Types and Arithmetic Operations.
Lecture 3: More Java Basics Michael Hsu CSULA. Recall From Lecture Two  Write a basic program in Java  The process of writing, compiling, and running.
Chapter 4 Mathematical Functions, Characters, and Strings 1.
1.  Algorithm: 1. Read in the radius 2. Compute the area using the following formula: area = radius x radius x PI 3. Display the area 2.
Week 3 - Monday.  What did we talk about last time?  Using Scanner to get input  Basic math operations  Lab 2.
Chapter 4: Mathematical Functions, Characters, and Strings
Chapter 4 Mathematical Functions, Characters, and Strings
Week 3 - Wednesday CS 121.
String, Math and the char Type
Chapter 4 Mathematical Functions, Characters, and Strings
Multiple variables can be created in one declaration
Type Conversion, Constants, and the String Object
Primitive Types Vs. Reference Types, Strings, Enumerations
Week 3: Basic Operations
OUTPUT STATEMENTS GC 201.
Primitive and Reference Data Values
Chapter 5 – Part 2 Methods Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved
CS 177 Week 3 Recitation Slides
Chapter 4: Mathematical Functions, Characters, and Strings
Chapter 2 Variables.
Chapter 3 Mathematical Functions, Strings, and Objects
ECE 103 Engineering Programming Chapter 8 Data Types and Constants
CS2011 Introduction to Programming I Strings
Primitive Types and Expressions
Chapter 4 Mathematical Functions, Characters, and Strings
Ch 5 : Mathematical Functions, Characters, and Strings
Presentation transcript:

CS 201 California State University, Los Angeles

 Various Mathematical Functions  Characters  Strings

 We have a lot of various mathematical methods in Java  We’ve covered 2 so far: Pow  exponent method Random  service method(min, max, absolute)  There are also many trigonometric methods We will cover…

 Similar to pow, these methods are all in the Math (java)Class Format is the same:  Math.methodName  Math.pow  Math.sin Note: the Math Class is in the java.lang package, and therefore doesn’t have to be imported  Everything in java.lang is implicitly included in a Java program

 sin(r)Value of sine in radians  cos(r)Value of cosine in radians  tan(r)Value of tangent in radians  toRadians(d)Convert degrees into radians  toDegree(r)Convert radians into degrees (Note: “degree” is singular!)  asin(a)Angle (in radians) of inverse sine  acos(a)Angle (in radians) of inverse cosine  atan(a)Angle (in radians) of inverse tangent

 Keep in mind most trig method arguments are angles measured in radians  Remember the range of radians: 0 to 2 π Unit circle!

 The Math Class also contains two constants, PI and E Both are doubles Access both using Math.constantName Math.PI  f Math.E  f

 Simply methods that are related to exponents: From the Math Class  Math.methodName  exp(n)Raises the value of e to the power n  log(n)Natural Logarithm of n  log10(n)Log 10 (n)  pow(a,b)Exponent, or a b  sqrt(n)The square root of n

 There are also methods to round numbers Again, from the Math Class  Math.methodName  ceil(x)Ceiling of x  floor(x)Floor of x  rint(x)x rounded up to nearest integer  If x is equally close to two integers, the even one is returned as a double  round(x)rounds  (int)Math.floor(x+0.5) for integers  (long)Math.floor(x + 0.5) for doubles  Note: For exactly halfway values (4.5), round(x) rounds up (5), while rint(x) rounds down (4)

 Contains min, max, abs, random min(a,b)  Returns the minimum of both numbers  Works for int, long, float, double max(a,b)  Returns the maximum of both numbers  Works for int, long, float, double abs(x)  Returns the absolute value of x  Works for int, long, float, double

 Range review  a + Math.random() * b Returns a random number between a and a+b, excluding a+b How do I get a random number between 15 and 20? 400 – 4000?

 Compute the angles of a triangle p123

 Distance Formula p124

 We can include (and process) characters in Java! We use the char data type We use character literals to specify characters  Type in a character between single quotes Characters are stored in UNICODE  Way to store international characters  Each number is matched to a character (in a language)  Was 16-bit, but that wasn’t enough space (!!!)

 Unicode International Characters Now holds up to 1,112,064 characters  ASCII  (American Standard Code for Information Interchange)  8-bit encoding scheme  Used in most computers  (Western characters)

 If you don’t want to input characters with string literals, you can use Unicode values Takes 2 bytes (both in hex), preceded by \u  \u03b1  \u03b2 Note: The first 128 values in Unicode are exactly the same in ASCII, making the characters compatible  Between \u0000 and \u007F

 You can use either ASCII or Unicode Ex:  char letter = ‘A’;  char letter = ‘\u0041’; Note: You can also use increment and decrement to get the previous or next character!  char a = ‘a’;  ++a;  System.out.println(a);

 If you want to use special characters that are used by the system, computer, or Java, you must use escape sequences Ex: (quotes, tabs, backslashes) These represent the characters without actually writing them Use the backslash and then a specific character to specify  Backslash (\) called an escape character

 Different escape sequences \bbackspace \tTab \nLinefeed \fFormfeed \rCarriage return \\Backslash \”Double quote

 You can cast a char into a numeric type Only the lower 16-bits of data are used  You can cast a number into a char Converted to Unicode Floating-point values are cast to int first  Numbers between 0 and FFFF in hex are implicitly casted into a char Anything else must be explicitly casted

 You can compare characters using relational operators  Results are generated using Unicode values What is the result of: ‘a’ < ‘b’ ? ‘1’ < ‘2’

 There are different methods of testing characters in the Character class isDigit(ch)Returns true if ch is a digit isLetter(ch) Returns true if ch is a letter isLetterOrDigit(ch) Returns true if ch is a letter or a digit isLowerCase(ch) Returns true if ch is lowercase isUpperCase(ch) Returns true if ch is uppercase toLowerCase(ch) Returns the lowercase version of ch toUpperCase(ch) Returns the uppercase version of ch

 Keep in mind that char represents only one character!  If you want to store multiple characters (or a string of characters) you need a String data type Ex: String message = “Strings can store a lot more than char”; The String data type is a reference type (not a primitive)  Predefined class in Java (like System and Scanner)  Any Java class can be used as a reference type for a variable

 The String class has its own methods. You can access these methods by using the dot (.) operator Methods:  length()Returns the number of characters in the string  charAt(index)Returns the character at the index value  concat(s1)Returns a new string that concatenates the current string with string s1  toUpperCase()Returns a new string with all letters in uppercase  toLowerCase() Returns a new string with all letters in lowercase  trim()Returns a new string with whitespace (spaces) trimmed (removed) on both sides

 The previous methods can only be used after a string object has been created (instantiantion) Methods are called instance methods Variable.methodName(arguments)  The Math methods can be used without creating a Math class These methods are called static methods ClassName.methodName(arguments)

 String Length  Getting Characters  Concatenation  Converting Case

 You can read in a String through console in (Scanner) input.next();  Reads in everything to a whitespace character nextLine()  Reads in the entire line of text Important! Do not use nextLine() after nextByte(), int, double, etc.

 To read in a char, use nextLine(), then use the method charAt(0); to return a character

 There are methods to Compare Strings: equals(s1)Returns true if the string is equal to s1 equalsIgnoreCase(s1)Case-insensitive version of equals compareTo(s1) Returns an integer >0, =0, s1 equal to s1 or >s1 compareToIgnoreCase(s1)Case insensitive verision of compareTo StartsWith(prefix)Returns true if the string starts with the prefix endsWith(suffix) Returns true if the strings ends with the suffix contains(s1)Returns true if s1 is a substring

 Note: You may be tempted to use the comparison operator (==) in order to compare strings DO NOT DO THIS!!!!!!! Just checks if the strings are the same object!  Do not use relational operators(,=, etc) to compare strings!

 You may need to get substrings from your string Substrings = Strings within strings substring(beginIndex)  Returns substring that begins with the character at the index  Note: The first index is 0 substring(beginIndex, endIndex)  Returns substring the begins with the character at index, and ends at endIndex - 1

 There are many different methods that find the position (index) of a character or substring within a string  These methods will return -1 if unmatched  indexOf(ch)Returns the index of the first occurrence of ch in the string.  indexOf(ch, fromIndex) Returns the index of the first occurrence of ch in the string after fromIndex.  indexOf(s) Returns the index of the first occurrence of the string s1.  indexOf(s, fromIndex)Returns the index of the first occurrence of the string s1.  lastindexOf(ch)Returns the index of the last occurrence of ch in the string.  lastindexOf(ch, fromIndex) Returns the index of the last occurrence of ch in the string after fromIndex.  lastindexOf(s) Returns the index of the last occurrence of the string s1.  lastindexOf(s, fromIndex)Returns the index of the last occurrence of the string s1.

 You can convert a numeric string into a number Use the Integer.parseInt() method  From the Integer class  Static method Can also use Double.parseDouble()  Static method

 You can use System.out.printf() to display formatted output on the console  Within the text use different format specifiers %bboolean value %ccharacter %ddecimal (integer) %f floating-point number %ea number in scientific notation %sa string

 If you put different variables in the printf, append them after the string using commas System.out.printf(“The Length is %d, area is %f”,length, area);

 You can format different precisions using System.out.printf() P147 Let’s do some examples!

 For character (c) and boolean (b) %[width]c %[width]b This separates out the number of spaces displayed in the area. Value is displayed on the left  Called the width Ex:  %5c  Specifies 5 spaces for the character. (Adds 4 spaces, then displays the character  %6b  Specifies 6 spaces for the result (Adds 1 extra space for false, 2 spaces for true)

 For floating-point values: %[width].[number_of_decimals]f %[width].[number_of_decimals]e First number specifies the minimum width Next number specifies the number of decimals shows  Note: The decimal is included in the width! Ex: %5.2f  Displays at least 5 spaces for width, and only 2 after the decimal (if there are more digits left of the decimal, they will be displayed

 For integers and strings: %[width]d %[width]s Displays a minimum width for displaying integers or strings If int or string is wider than minimum, it will automatically expand.