# Lecture 8 Using casts, Strings and WordUtil - PowerPoint PPT Presentation

1 / 10

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 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?

I am the owner, or an agent authorized to act on behalf of the owner, of the copyrighted work described.

Lecture 8 Using casts, Strings and WordUtil

Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author.While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server.

- - - - - - - - - - - - - - - - - - - - - - - - - - E N D - - - - - - - - - - - - - - - - - - - - - - - - - -

## Lecture 8Using casts, Strings and WordUtil

### 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

• checking the length of a String

• can we cast a String into an int?

• Or an int to a String?

• Using the WordUtil class

### 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)

### 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

### 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)

### String class

• Create a String:

• String word;

• word = "hello";

• word = in.next(); // in is a Scanner object

• Compare 2 strings

• if ( word.equals("hello")) { ...println("good morning");

}

### 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 )

### Remember the 3 Different Kinds of Classes ?

• Application Class – what we've been doing

• Has public static void main ( String [] args)

• Instantiable Class – use to make objects from

• String, Scanner

• Classes with only static utility methods

• like Math class

### WordUtilclass – another class with static utility methods

• How to get the 15th word?

• How to check if a word is in the dictionary?