Presentation is loading. Please wait.

Presentation is loading. Please wait.

Lecture 8 Using casts, Strings and WordUtil. Agenda Generating random numbers Casts – Casting a double into an int – Casting an int into a char – Casting.

Similar presentations


Presentation on theme: "Lecture 8 Using casts, Strings and WordUtil. Agenda Generating random numbers Casts – Casting a double into an int – Casting an int into a char – Casting."— Presentation transcript:

1 Lecture 8 Using casts, Strings and WordUtil

2 Agenda Generating random numbers Casts – Casting a double into an int – Casting an int into a char – Casting a char into an int Strings again – reading a String – checking the length of a String – can we cast a String into an int? – Or an int to a String? Using the WordUtil class

3 Generating Random Numbers Recall Lab2 the Math.random() method: – double myNumber; – myNumber = Math.random(); // (from 0 to.999) Then in Lab5: – double secret; – secret = Math.round(Math.random()*100); 0 to 100 ( 0 and 100 come up half as often as others) – OR secret = (int)( Math.random()*100); 0 to 99 ( evenly distributed)

4 A Cast "filters" a value into a different type int x = (int) 4.1243; // x gets 4 double z = 56.23; int y = (int) z; // y gets 56, z remains 56.23 z = (double) y; // z gets 56.0 char letter = 'c'; int code = (int) letter; // code gets 97 letter = (char) 65; // letter gets 'A' letter = 'A'; // this is more clear, same value

5

6 For this lab We'll use casts to convert a random double to int – int num = (int)( Math.random()*100); 0 to 99 ( evenly distributed)

7 String class Create a String: – String word; – word = "hello"; Read a String – word = in.next(); // in is a Scanner object Compare 2 strings – if ( word.equals("hello")) {...println("good morning"); }

8 How long is a String Print the length: –...println("length of word = " + word.length() ); Check if the length is 5 letters: – if ( word.length() == 5 )

9 Remember the 3 Different Kinds of Classes ? 1.Application Class – what we've been doing – Has public static void main ( String [] args) 2.Instantiable Class – use to make objects from – String, Scanner 3.Classes with only static utility methods – like Math class

10 WordUtilWordUtil class – another class with static utility methods How to get the 15 th word? How to check if a word is in the dictionary?


Download ppt "Lecture 8 Using casts, Strings and WordUtil. Agenda Generating random numbers Casts – Casting a double into an int – Casting an int into a char – Casting."

Similar presentations


Ads by Google