String, Math and the char Type

Slides:



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

L2:CSC © Dr. Basheer M. Nasef Lecture #2 By Dr. Basheer M. Nasef.
1 Chapter 2 Basic Elements of Fortran Programming.
1 Fundamental Data types Overview l Primitive Data Types l Variable declaration l Arithmetical Operations l Expressions l Assignment statement l Increment.
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.
Datalogi A 3: 26/9. Java Concepts chapter 4 Fundamental Data Types int (long and short) double (and float) boolean char String.
Lab session 3 and 4 Topics to be covered Escape sequences Escape sequences Variables /identifiers Variables /identifiers Constants Constants assignment.
Fundamental Programming Structures in Java: Comments, Data Types, Variables, Assignments, Operators.
Java Primitives The Smallest Building Blocks of the Language (corresponds with Chapter 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,
Unit 3: Java Data Types Math class and String class.
Characters The data type char represents a single character in Java. –Character values are written as a symbol: ‘a’, ‘)’, ‘%’, ‘A’, etc. –A char value.
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?
STANDARD FUNCTIONS Computer Programming Asst. Prof. Dr. Choopan Rattanapoka and Asst. Prof. Dr. Suphot Chunwiphat.
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All rights reserved. 1 Chapter 4 Mathematical Functions, Characters,
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.
1 Operations Making Things Happen (Chap. 3) Expressions.
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.
C# C1 CSC 298 Elements of C# code (part 1). C# C2 Style for identifiers  Identifier: class, method, property (defined shortly) or variable names  class,
Chapter 3: Classes and Objects Java Programming FROM THE BEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved Java’s String Class.
© Copyright 2012 by Pearson Education, Inc. All Rights Reserved. 1 Chapter 3 Mathematical Functions, Strings, and Objects.
Chapter-4 Managing input and Output operation.  Reading, processing and writing of data are three essential functions of a computer program.  Most programs.
A Simple Java Program //This program prints Welcome to Java! public class Welcome { public static void main(String[] args) { public static void main(String[]
CSC Programming I Lecture 9 September 11, 2002.
CSM-Java Programming-I Spring,2005 Fundamental Data Types Lesson - 2.
ITK 168 – More Variables 10/13/05. Another example of using instance variables and constants  Go through SimpleBot  Modify SimpleBot to “teleport”
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.
Formatted Output (printf) CSE 1310 – Introduction to Computers and Programming Vassilis Athitsos University of Texas at Arlington 1.
CS 201 California State University, Los Angeles.  Various Mathematical Functions  Characters  Strings.
Winter 2016CISC101 - Prof. McLeod1 CISC101 Reminders Quiz 3 this week – last section on Friday. Assignment 4 is posted. Data mining: –Designing functions.
CSE 110: Programming Language I Matin Saad Abdullah UB 1222.
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.
Strings A String is a sequence of letters
Simple C Programs.
Chapter 4: Mathematical Functions, Characters, and Strings
Formatted Input and Output
Chapter 4 Mathematical Functions, Characters, and Strings
Topics Designing a Program Input, Processing, and Output
Chapter 2 Basic Computation
BIL 104E Introduction to Scientific and Engineering Computing
TMF1414 Introduction to Programming
Multiple variables can be created in one declaration
Variables and Primative Types
Fundamental of Java Programming Basics of Java Programming
Primitive Types Vs. Reference Types, Strings, Enumerations
Chapter 2 Basic Computation
OUTPUT STATEMENTS GC 201.
Input/Output Input/Output operations are performed using input/output functions Common input/output functions are provided as part of C’s standard input/output.
IDENTIFIERS CSC 111.
Variables In programming, we often need to have places to store data. These receptacles are called variables. They are called that because they can change.
Chapter 4: Mathematical Functions, Characters, and Strings
String Manipulation Chapter 7 Attaway MATLAB 4E.
Chapter 2: Java Fundamentals
Chapter 3 Mathematical Functions, Strings, and Objects
elementary programming
Introduction to Java Applications
Topics Designing a Program Input, Processing, and Output
Topics Designing a Program Input, Processing, and Output
Fundamental OOP Programming Structures in Java: Comments, Data Types, Variables, Assignments, Operators.
In this class, we will cover:
Outline Creating Objects The String Class The Random and Math Classes
Ch 5 : Mathematical Functions, Characters, and Strings
Presentation transcript:

String, Math and the char Type Here we focus on the Math class, the String class, and the char type The Math class is not like Scanner or Random because it does not need to be imported it is also not like Scanner, Random or String because we do not create a variable of type Math, instantiate it and pass messages to that variable instead we pass messages directly to the Math class itself Math.message(params); We have already seen 4 messages: abs, pow, random, sqrt, others include exp(x) – return the value of ex (e is a mathematical constant) log(x) – return the value of log e x (this is known as the natural log) log10(x) – return the value of log 10 x sin(x), cos(x), tan(x) – x is in radians and returns an angle asin(x), acos(x), atan(x) – x is an angle and returns a value in radians toRadians(x) – returns angle x in radians toDegree(x) – returns radian x in degrees All of these methods return double values but can accept int or double (or float) params

More Math Methods For rounding values ceil(x) – x is rounded up to the next integer but returned as a double floor(x) – x is rounded down to the nearest integer but returned as a double rint(x) – x is rounded up to the nearest integer and returned as a double, but if the number is exactly halfway (.5), it returns the value that is even (e.g., rint(5.5) returns 6.0 and rint(6.5) returns 6.0) round(x) – adds .5 to x and then truncates the value, returning an int (or a long if x is a double) Minimum and maximum are min(x, y) and max(x, y) these return whatever type is wider between x and y if x is an int and y is a double, it returns a double Absolute value is abs(x) and it returns whatever type x is Math.abs(-5) is 5 while Math.abs(-5.1) is 5.1 Math has defined constants for E and PI denoted as Math.E and Math.PI

The char Type The char type stores a single character placed in ‘ ’ when specified as a literal Java supports both ASCII and Unicode characters ‘a’ and ‘A’ are different characters Unicode values are stored in at least 2 bytes but may be longer (Unicode now incorporates over 1 million characters) by default, all characters on the keyboard are stored in ASCII to store a character not on the keyboard, you must indicate its Unicode number as a hexadecimal value (0-9, A-F as in 03b1 which is the Greek alpha letter) To indicate that a set of hexadecimal digits should be encoded in Unicode, precede the value with \u as in char x = ‘\u03b1’; the \ is the escape character which is used to “treat a character by special meaning” Other useful escape characters are ‘\n’ is a carriage return ‘\t’ is a tab ‘\\’ represent a backslash See more on page 126

Operations on chars We can compare chars using <, >, <=, >=, ==, != for instance (x >= ‘a’ && x <= ‘z’) We can add to and subtract from chars for instance, char x = ‘a’; x++; // x now stores ‘b’ Cast between int and char types if we have a value stored in an int, casting it to a char means that we are taking that number and exchanging it with the ASCII value at that position in the ASCII table for instance: int i = 97; char c = (char)i; // c is now ‘a’ or: char c = ‘a’; int x = (int)c – 10; // x is 87 consider int y = ‘1’ + ‘2’; // ‘1’ is 49, ‘2’ is 50, y = 99 If we add to a char (e.g., c + 1), the value is coerced into an int, we need to cast it back to a char if we want it to be treated as a char: char c = ‘a’; c = (char)(c + 1); // c + 1 is 98, (char)c is ‘b’

The Character Class Do not confuse char and Character char is a primitive type Character is a class whose objects store single char values Why do we need Character? We don’t usually But Character has some useful built-in methods that we might want to apply to a char isDigit(ch) – true if ch is a digit (‘0’, ‘1’, … ‘9’) isLetter(ch) – true if ch is a letter (upper or lower case) isLetterOrDigit(ch) – true if ch is a letter or a digit isLowerCase(ch), isUpperCase(ch) – case of ch must match toLowerCase(ch), toUpperCase(ch) – returns the version of ch with the new case if ch is a letter, otherwise it returns ch unchanged We reference the above methods like we would Math by passing them directly to the Character class as in Character.isDigit(ch)

The String Class The String class, like Math and Char, is built-in so we don’t import it But we do have to declare variables of type String and use them String gives us a shortcut on instantiation though, we can use new but we don’t have to String someString = new String(“some value”); or String someString = “some value”; As Strings are objects, we pass them messages we do not treat them like the primitive types so instead of <, >, ==, etc, we use compareTo and equals/equalsIgnoreCase the only arithmetic operator available for Strings is + to perform String concatenation as in str3 = str1 + str2; We can store the “empty string” in a String (we might do this to initialize a String) String someString = “”;

String Methods str1.equals(str2), str1.equalsIgnoreCase(str2), str1.compareTo(str2) – as we covered in chapter 3 str1.length( ) – returns the number of characters stored in str1 str1.concat(str2) – concatenation, same as str1 + str2 str1.charAt(i) – returns the character at index i of str1 the first character is at index 0 if str1 = “hello” then str1.charAt(0) is ‘h’, str1.charAt(1) is ‘e’, etc str1.toUpperCase( )/str1.toLowerCase( ) returns str1 where all letters are changed to the case specified, non-letters are unchanged str1.replace(char1, char2) – returns a version of str1 where every instance of character char1 is replaced by char2 str1.trim( ) – return a version of str1 with white space removed note: Strings are immutable, these methods do not change str1, merely return a new String which is a copy of str1 except with the specified change(s)

Example public class StringExample { public static void main(String[] args) { String str1 = “hello there!”; String str2, str3; str2 = str1.toUpperCase( ); System.out.println(str1 + “ ” + str2); str2 = str1.replace(‘E’, ‘3’); str3 = str2.concat(str1); System.out.println(str3); System.out.println(str1.charAt(0) + “ ” + str2.charAt(0)); System.out.println(str1.trim()); System.out.println(str1); } Output: hello there HELLO THERE hello there H3LLO TH3R3 H3LLO TH3R3hello there h H hellothere hello there

Other String Methods str1.startsWith(str2)/str1.endsWith(str2)/str1.contains(str2) returns true if str1 starts/ends with the substring str2 or contains str1 characters of str2 must be found consecutively in str1 to match str1.substring(i) returns the portion of str1 starting at index i until the end of the str1 str1.substring(i, j) returns the portion str1 starting at index i up to but not including index j if str1 = “abcdefg” then str1.substring(3, 6) returns “def” str1.index(ch)/str1.index(s) returns the index of the first occurrence of the character ch or String s in str1 str1.indexOf(ch, i)/str1.indexOf(s, i) returns the index of the first occurrence of the character ch or String s in str1 starting at index i there are also lastIndexOf(ch), lastIndexOf(s), lastIndexOf(ch, i), lastIndexOf(s, i) where it searches backward from the end of the String until it finds ch or s remember: the first character of a String is at index 0, not 1!

Converting Strings and Other Types To obtain a single character of a string use str1.charAt(i) for instance, to input a char instead of a String use in.next().charAt(0); If a String is storing a numeric value (for instance “12345” or “1.2345”) you can obtain the numeric version of it as an int, float or double Integer.parseInt(str1) Float.parseFloat(str1) Double.parseDouble(str1) if the String is not storing the type being parsed for, you get a run-time Exception To convert a number to a String, use the following notation, assume x is a numeric type (int or double) String y = “” + x; // “” is the empty String, + concatenates x onto it Integer, Double and Float classes are automatically loaded like Math, Character and String so no importing is needed

Formatted Output Recall earlier outputting values stored in double variables may give us more decimal points of accuracy than desired We can use System.out.printf to format our output printf formatting is similar to C/C++’s printf Syntax: System.out.printf(“specification string”, var, var, var, …); the specification string includes any literal output along with format specifiers for every variable a format specifier is %d.dc where d.d specifies the size and c specifies the type of datum use %dc for int and String where d is the minimum width use %d.dc for floating point values where the first d is the minimum width of the output of the floating point value and the second d is the number of decimal points of precision minimum width will cause the output to be padded with blank spaces on the left the d’s can be omitted add a hyphen(-) after % if you want the variable to be left justified

Specifier Information The following letters are used to indicate the type to output %b (boolean) %c (char) %d (decimal integer) %f (floating point number – double or float) %e (floating point number in scientific notation) %s (String) When using .d for floating point, remember that the decimal point counts as a character When using d, if your value is too small for the output, the d is ignored (for instance, “%5d” and the variable is a 7-digit number, all 7 digits are output Examples %15s – a String of 15 characters (add blanks to the left to fill out the 15 spaces as needed) %6d – an int value to 6 total spaces (add blanks as needed) %5.2f – a floating point value with 2 decimal points of accuracy and 5 total characters including the decimal point %2c – output the character but add a blank space before the character

Example public class FormattingDemo { public static void main(String[] args) { int degrees = 30; double radians = Math.toRadians(degrees); System.out.printf("%-10s%-10s%-10s%-10s%-10s\n", "Degrees", "Radians", "Sine", "Cosine", "Tangent"); System.out.printf("%-10d%-10.4f%-10.4f%-10.4f%-10.4f\n", degrees, radians, Math.sin(radians), Math.cos(radians), Math.tan(radians)); degrees = 60; radians = Math.toRadians(degrees); } Degrees Radians Sine Cosine Tangent 30 0.5236 0.5000 0.8660 0.5774 60 1.0472 0.8660 0.5000 1.7321