Working with Text and Numbers in Java

Slides:



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

Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 1 Chapter 9 Strings.
Building Java Programs
Computer Programming w/ Eng. Applications
Return values.
Self Check 1.Which are the most commonly used number types in Java? 2.Suppose x is a double. When does the cast (long) x yield a different result from.
1 Strings and Text I/O. 2 Motivations Often you encounter the problems that involve string processing and file input and output. Suppose you need to write.
Copyright 2011 by Pearson Education Building Java Programs Chapter 3 Lecture 3-2: Return values, Math, and double reading: 3.2,
Copyright 2006 by Pearson Education 1 Building Java Programs Chapter 3: Parameters, Return, and Interactive Programs with Scanner.
Numerical Data Recitation – 01/30/2009
Lecture 6 29/1/15. Number functions Number functions take numbers as input, change them, and output the results as numbers. 2.
Week #2 Java Programming. Enable Line Numbering in Eclipse Open Eclipse, then go to: Window -> Preferences -> General -> Editors -> Text Editors -> Check.
Working with Numbers in Alice - Converting to integers and to strings - Rounding numbers. - Truncating Numbers Samantha Huerta under the direction of Professor.
10/25: Methods & templates Return to concepts: methods Math class methods 1 st Program of the day About DrawLine.java modifications Method definitions.
Variable Declaration  It is possible to declare multiple variables of the same data type on the same line.  Ex. double hours, rate, total;  Variables.
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All rights reserved. 1 Chapter 4 Mathematical Functions, Characters,
Objects and Classes; Strings. 2 Classes and objects class: A program entity that represents either 1.A program / module, or 2.A type of objects* –A class.
ITI 1120 Lab #7. Agenda Topics in this lab: –Methods & Arrays –Library classes –Testing (JUnit) –Strings In this lab, you are going to create your own.
GCOC – A.P. Computer Science A. College Board Topics – A.P. Computer Science A Program Design - Read and understand a problem's description, purpose,
Copyright 2011 by Pearson Education Building Java Programs Chapter 3 Lecture 7: Return values, Math, and double reading: 3.2,
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All rights reserved. 1 Chapter 4 Mathematical Functions, Characters,
Math With Java The Math Class. First, A Quick Review of Math Operators in Java Primitive Data type in Java that represent numbers: Primitive Data type.
Math Class Part of the Java.lang package. This package is from object so you do not have to import the lang package. Static: Math Class is static.
Strings Mr. Smith AP Computer Science A. What are Strings? Name some of the characteristics of strings: A string is a sequence of characters, such as.
Lecture 12: Final Review Tami Meredith. Programming Requires 1. Identification of the problem Understanding it, identifying correct solutions 2. Solving.
The Math Class Methods Utilizing the Important Math Operations of Java!
1 Java Library Lecture 9 by Dr. Norazah Yusof. 2 Java Library Java has pre-defined classes that consist of the basic language classes in Java (organized.
Math Class Mrs. C. Furman September 2, Math frequently used methods NameUse floor()rounds down ceil()rounds up pow(x,y)returns x to the power of.
Strings Methods in the String class Manipulating text in Java.
Creating and Using Class Methods. Definition Class Object.
1 Project 2: Using Variables and Expressions. 222 Project 2 Overview For this project you will work with three programs Circle Paint Ideal_Weight What.
Special Methods in Java. Mathematical methods The Math library is extensive, has many methods that you can call to aid you in your programming. Math.pow(double.
Simple Console Output. What we will briefly discuss System.out.println( … ) System.out.print( … ) System.out.printf( … )
Copyright 2011 by Pearson Education Building Java Programs Chapter 3 Lecture 3-2: Return values, Math, and double reading: 3.2,
Lecture 5: java.lang.Math, java.lang.String and Characters Michael Hsu CSULA.
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.
The Methods and What You Need to Know for the AP Exam
Introduction to python programming
Chapter 4: Mathematical Functions, Characters, and Strings
Some Assignments  Write a program which prints the following information about at least 5 persons: NAME MAIL-ID EMPLOYEE-CODE PHONE Eg. Umesh
Chapter 4 Mathematical Functions, Characters, and Strings
Lecture 6: While Loops and the Math Class
Chapter 2 More on Math More on Input
Introduction to Python
Program: Shape Area Print the area for various shape types using the respective formulas.
Building Java Programs
Chapter 4 Mathematical Functions, Characters, and Strings
2.5 Another Java Application: Adding Integers
Java Coding 3 – part2 David Davenport Computer Eng. Dept.,
MATHS Week 8 Geometry.
Subroutines Idea: useful code can be saved and re-used, with different data values Example: Our function to find the largest element of an array might.
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.
Section 6.2 Classes & Objects.
Chapter 4: Mathematical Functions, Characters, and Strings
The Math class The java.lang.Math class contains methods for performing basic numeric operations such as the elementary exponential, logarithm, square.
Number and String Operations
Truth tables: Ways to organize results of Boolean expressions.
Truth tables: Ways to organize results of Boolean expressions.
Wednesday 09/23/13.
Coding Concepts (Data- Types)
Building Java Programs
CHAPTER 3: String And Numeric Data In Python
Using Objects (continued)
Other types of variables
Unit 3: Variables in Java
Random Numbers while loop
Methods in the String class Manipulating text in Java
Ch 5 : Mathematical Functions, Characters, and Strings
Presentation transcript:

Working with Text and Numbers in Java The Math & String Classes

The Math Class The Math class is a special class called a static class, there is no need to create a Math object, instead we ask the class directly Static class Math.PI//value of PI Non static class String name = new String(”Joe”); You can now use name in your code

Math class All of the buttons you find on your calculator are in the Math class sin, cos, tan sqrt, pow, etc. Of course you can find them all in the JavaDoc Official Oracle Documentation Another things you’ll need to use in the Math class is random numbers

Math Methods double Math.ceil( double value ) This method rounds up a floating point number It also returns a floating point so be sure to cast if you’re putting the result in an int Ex. double ceil = Math.ceil( 10.9 ); //returns 11.0 double ceil = Math.ceil( 3.1 ); //returns 4.0 double ceil = Math.ceil( -1.9 ); //returns -1.0 int ceil = (int)Math.ceil( -1.2 ); //returns -1.0

Math Methods double Math.floor( double value ) This method rounds down a floating point number It also returns a floating point so be sure to cast if you’re putting the result in an int Ex. double floor = Math.floor( 3.1 ); //returns 3.0 double floor = Math.floor( 10.9 ); //returns 10.0 double floor = Math.floor( -1.2 ); //returns -2.0 int floor = (int)Math.floor( -1.9 ); //returns -2.0

Math Methods double Math.pow( double base, double exponent ) This method returns the power of (base)exponent It also returns a floating point so be sure to cast if you’re putting the result in an int Ex. double power = Math.pow( 2, 3 ); //returns 8.0 double power = Math.pow( 3, 4 ); //returns 81.0 double power = Math.pow( 0.1, 5 ); //returns 0.00001 int power = (int)Math.pow( 1.5, 2 );//returns 2.25 (it is cast to 2)

Math Methods double Math.abs( double value ) This method returns the absolute value of value It also returns a floating point so be sure to cast if you’re putting the result in an int Ex. double absolute = Math.abs( 100 ); //returns 100.0 double absolute = Math.abs( -4.5); //returns 4.5 double absolute = Math.abs( 0.57 ); //returns 0.57 int absolute = (int)Math.abs( -1234 ); //returns 1234

Math Methods double Math.sqrt( double value ) This method returns the square root of value It also returns a floating point so be sure to cast if you’re putting the result in an int Ex. double root = Math.sqrt( 100 ); //returns 10.0 double root = Math.sqrt( 2 ); //returns 1.4142 double root = Math.sqrt( 0.25 ); //returns 0.5 int root = (int)Math.sqrt( 16.0 ); //returns 4

Making a Formula in Java The quadratic formula: Using the order of operations we get, x1 = ( –1*b + Math.sqrt( Math.pow( b, 2 ) – 4*a*c ) ) / (2*a) Can you rewrite the other solution? x2 = (–1*b – Math.sqrt( Math.pow( b, 2 ) – 4*a*c )) / (2*a)

Math.random() Random numbers can be generated from the random method of the Math Class static double random(); returns a random number between 0.0 (inclusive) and 1.0 (exclusive) Ex. double randomNumber = Math.random() * 100; This is a random number between 0.0 and 99.999999

Using Math.random Ex. double randomNumber = Math.random() * 35; Between 0.0 and 34.9999999999 double randomNumber = Math.random() * 50 + 10; Between 10.0 and 59.999999999 int randomNumber = (int)(Math.random() * 20) + 5; Between 5 and 24 don’t forget to cast with ints Notice the range is 5 to 24! Math.random() * 20 returns 0 to 19.999999999999… (int)(Math.random() * 20) chops off all decimals Returns 0 to 19

Be Careful When Casting! (int)Math.random() * 20 + 5; returns 5 every time your program is run: Generate a random value, say 0.774312 Cast it to an it Now it has the value 0 0 * 20 = 0 0 + 5 = 5

Using Math.random If you want to generate a number in the range [a,b)  not including b (as doubles) Math.random()*(b – a) + a If you want to generate a number in the range [a,b] (as ints) (int)(Math.random()*(b – a+1)) + a

Math Programming Exercises Create a program that asks the user to click the first time to indicate the center of a circle Tell the person to click again to indicate the a point on the radius of the circle The way this is done is you must calculate the distance between the two points and use that for the radius (along with the center they already clicked) when you create the circle.

Math Programming Exercise Have the user click on 3 points on the screen to draw a triangle. Display a message to the user that tells them the length of each side, its perimeter and its area. To calculate the length or each side you can use the distance formula on the previous slide To label the three sides you can use the midpoint of the two end points: To calculate the area you can use Heron’s Formula Label the area in the center of the triangle using its Centroid: Make sure to create methods for each of your tasks (not just voids)!

Math Programming Exercises Create a program that will draw a random polygon every time it is run. Use a minimum of 5 points. Your points must be drawn on the screen! Do not restrict the values to being integers (the graphics window can draw floating point coordinates) You can do this by randomly generating the coordinates of each point you put in the JPolygon. Make the color of the JPolygon random also Do this by generating three random numbers (red, green and blue) for the fill and border color. The numbers should be from 0 to 255

The String Class Like all standard java classes, there is a javadoc for the String class that can be helpful to you. The methods our class is responsible for are: length() indexOf( String ) indexOf( String, int ) substring( int, int ) substring( int )

How Java Deals With Text Strings in Java are stored in memory as a consecutive sequence of characters Each character has an index to refer to its location The first index in every String is zero Ex. String phrase = “JAVA IS COOL”; Character J A V I S C O L Index 1 2 3 4 5 6 7 8 9 10 11

The length method Strings can tell you how long they are by using the length method: Scanner in = new Scanner( System.in ); System.out.println( “Please Enter Your Name: “ ); String name = in.nextLine(); int nameLength = name.length();//count the characters in name System.out.println( “There are “ + nameLength + ” characters “ + “in your name.” );

The indexOf method There are two indexOf methods, the first is a method where the string will find the first occurrence of an expression within the word. Ex. String example = “TESTING”; int result = example.indexOf( “S” );// returns 2 int result = example.indexOf( “TIN” );// returns 3 int result = example.indexOf( “T” );// returns 0, first T found int result = example.indexOf( “Q” );// returns -1 if not found Character T E S I N G Index 1 2 3 4 5 6

The indexOf Method The other indexOf method takes an extra parameter that tells it where to start looking Ex. String example = “TESTING”; Character T E S T I N G Index 0 1 2 3 4 5 6 int result = example.indexOf( “T”, 1 );// returns 3, first T after index 1 int result = example.indexOf( “E”, 2 );// returns -1, no E after index 2 int result = example.indexOf( “N”, 3 );// returns 5, first N after index 3

indexOf Practice Let’s try a few indexOf examples together I’ll put the examples on the whiteboard and your job is to tell me what value is returned Remember, strings are 0-based if the expression is not found -1 is returned The first location is returned unless you tell the method where to start

The substring Method The substring method allows you to extract pieces of a string The first version we’ll look at takes one parameter, where to start the substring Ex. String example = “substring method”; System.out.println( example.substring( 10 ) );//prints “method” System.out.println( example.substring( 3 ) );//prints “string method” System.out.println( example.substring( 13 ) );//prints “hod”

The substring Method The second version of substring takes two parameters, pay CAREFUL attention! The place to start (inclusive) One space past the end (exclusive) String example = “substring method”; System.out.println( example.substring( 0,3 ) );//prints “sub” System.out.println( example.substring( 3,9 ) );//prints “string” System.out.println( example.substring( 10,16 ) );//prints “method”

substring Practice The substring method can be tricky Especially when there are two parameters The first one is the starting index The second one is ONE PAST the index you want to end at If you only specify the starting position, then substring will go to the end of the string Let’s try some together

Other String Methods I encourage you to refer to the JavaDoc online for Strings, there are many methods that you may find helpful as we create new projects. Later on I will review with you the methods: equals compareTo Some suggestions that can be helpful: replace trim valueOf toUpperCase toLowerCase matches You’ll also need to learn about a very useful programming concept called regular expressions in order to use this method

String Exercises Write a program that separates your full name (first, middle and last) using the substring method Ex. String name = “John Jacob Smith”; System.out.println… Output will be: John Jacob Smith

String Exercises Create a program that reads a line of text from the user and tells them the first and last characters which were entered. Ex. Enter your text: Hello World! First Character: H Last Character: !

String Exercises Create a program that reads in a word from a user and separates it into two halves then puts it back together in the wrong order: Ex. Please enter your text: NetBeans First Half: NetB Second Half: eans Scrambled: eansNetB

String Exercises Write a program to retrieve a specific character for a user. Ex. Enter your text: This is a test Which character do you want me to find: 4 The character is: “s” *Remember, Strings are zero based but the user is giving you the position as though it started at 1

String exercises Repeat the first substring program but this time ask the user for their full name and split their name apart using the substring and indexOf methods (hint, the “ “ marks the start/end of each word)