Java for Beginners

October 4th, 2023


Week 4: Standard Classes and Libraries

Class 7: Introduction to Standard Java Classes

Introduction to Standard Classes

In this class, we will explore some of the standard Java classes and libraries that provide useful functionality for common programming tasks. These classes are part of the Java Standard Library and can save you time when developing Java applications.

String Class

The String class is one of the most commonly used classes in Java. It represents sequences of characters and provides various methods for working with strings.

String greeting = "Hello, World!";
int length = greeting.length(); // Returns the length of the string (13)
String uppercase = greeting.toUpperCase(); // Converts the string to uppercase

Math Class

The Math class provides mathematical functions and constants. It is useful for performing mathematical calculations in your Java programs.

double pi = Math.PI; // The value of π (pi)
double sqrt = Math.sqrt(16); // Square root of 16
double random = Math.random(); // Generates a random double between 0.0 (inclusive) and 1.0 (exclusive)

Random Class

The Random class allows you to generate random numbers. You can use it to introduce randomness into your programs or simulate unpredictable behavior.

import java.util.Random;

Random random = new Random();
int randomNumber = random.nextInt(100); // Generates a random integer between 0 (inclusive) and 100 (exclusive)

Commonly Used Functions from the Random Class in Java

The Random class in Java, which is part of the java.util package, provides methods for generating random numbers. These methods are commonly used for various applications, including simulations, games, and randomness in program behavior. Here are some commonly used functions from the Random class:

  1. nextInt(int bound): Generates a random integer between 0 (inclusive) and the specified bound (exclusive). For example:

    Random random = new Random();
    int randomNumber = random.nextInt(10); // Generates a random integer between 0 and 9.
    
  2. nextDouble(): Generates a random double value between 0.0 (inclusive) and 1.0 (exclusive). For example:

    Random random = new Random();
    double randomValue = random.nextDouble(); // Generates a random double between 0.0 and 1.0.
    
  3. nextBoolean(): Generates a random boolean value (true or false). For example:

    Random random = new Random();
    boolean randomBoolean = random.nextBoolean(); // Generates a random true or false.
    
  4. nextLong(): Generates a random long integer. For example:

    Random random = new Random();
    long randomLong = random.nextLong(); // Generates a random long integer.
    
  5. nextFloat(): Generates a random float value between 0.0 (inclusive) and 1.0 (exclusive). For example:

    Random random = new Random();
    float randomFloat = random.nextFloat(); // Generates a random float between 0.0 and 1.0.
    

For more references, please refer to this link.

Practice with Standard Classes: Hot and Cold number game

Create a simple hot and cold number game where the program generates a random number, and the player has to guess it.

Requirements The program should provide hints to the player:

  • Hot: +/- 3 or less
  • Warm: +/- 10 or less
  • Cold: +/- 20 or less
  • Freezing: other

Hints

  • Use the Random class to generate the random number.
  • Use the Scanner class to take input from the player.
  • Use the Math.abs() method to calculate the absolute difference between the player’s guess and the random number.

Sample output

Welcome to the Hot and Cold Number Game!
I'm thinking of a number between 1 and 100. Try to guess it.
Enter your guess: 50
Clue: Warm
Enter your guess: 25
Clue: Freezing
Enter your guess: 75
Clue: Cold
Enter your guess: 65
Clue: Warm
Enter your guess: 55
Clue: Warm
Enter your guess: 45
Clue: Cold
Enter your guess: 57
Clue: Hot
Enter your guess: 58
Clue: Hot
Enter your guess: 59
Congratulations! You guessed the number in 9 guesses.

Here’s a sample code you can begin with:

import java.util.Random;
import java.util.Scanner;

public class HotAndColdGame {

    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        Random random = new Random();
        
        // COMPLETE HERE: Generate a random integer between 1 and 100
        int numberOfGuesses = 0;
        
        System.out.println("Welcome to the Hot and Cold Number Game!");
        System.out.println("I'm thinking of a number between 1 and 100. Try to guess it.");
        
        while (true) {
            System.out.print("Enter your guess: ");
            // COMPLETE HERE: Take in an integer input
            numberOfGuesses++;
            
            if (userGuess < 1 || userGuess > 100) {
                System.out.println("Please enter a number between 1 and 100.");
            } else if (userGuess == targetNumber) {
                // COMPLETE HERE: Print the end of the game sentence, together with the number of attempts made.
                break;
            } else {
                String clue = getClue(userGuess, targetNumber);
                System.out.println("Clue: " + clue);
            }
        }
        
        scanner.close();
    }
    
    // Method to provide clues based on the proximity of the guess
    private static String getClue(int guess, int target) {
        // COMPLETE HERE: Calculate the absolute difference between the guess and the target
        
        if (difference <= 3) {
            return "Hot";
        } else if (difference <= 10) {
            return "Warm";
        }
        // COMPLETE HERE: Handle the Cold and Freezing condition
    }
}

Pop Quiz

Quiz 1: Which standard Java class is used to represent sequences of characters?

  1. Math
  2. Random
  3. String
  4. Scanner

Quiz 2: What does the length() method of the String class return?

  1. The character at a specified index.
  2. The index of the first occurrence of a substring.
  3. The number of characters in the string.
  4. The uppercase version of the string.

Quiz 3: Which standard Java class is used for mathematical calculations and provides constants like π (pi)?

  1. String
  2. Math
  3. Random
  4. Scanner

Quiz 4: To generate random numbers in Java, which class is commonly used?

  1. String
  2. Math
  3. Random
  4. Scanner

Quiz 5: What is the purpose of the Random class in Java?

  1. To perform mathematical calculations.
  2. To generate random numbers.
  3. To work with sequences of characters.
  4. To read user input.

Answers:

  1. C
  2. C
  3. B
  4. C
  5. B

Class 8: Working with ArrayLists

Introduction to ArrayLists

In this class, we will explore the ArrayList class, which is a part of the Java Collections Framework. ArrayList provides a dynamic array-like data structure that can grow or shrink in size as needed. It is commonly used to store collections of objects.

Creating an ArrayList

To create an ArrayList, you need to import the ArrayList class and specify the type of objects it will hold (e.g., String, Integer).

import java.util.ArrayList;

ArrayList<String> names = new ArrayList<>();

Adding and Removing Elements

You can add elements to an ArrayList using the add() method and remove elements using the remove() method.

names.add("Alice");
names.add("Bob");
names.add("Charlie");

names.remove("Bob"); // Removes "Bob" from the ArrayList

Accessing Elements

You can access elements in an ArrayList by their index.

String firstPerson = names.get(0); // Retrieves the first element (Alice)

Iterating through an ArrayList

You can use loops to iterate through the elements of an ArrayList.

for (String name : names) {
    System.out.println(name);
}

ArrayList Methods

ArrayList provides various methods for working with lists, such as size(), isEmpty(), contains(), and more.

int size = names.size(); // Returns the number of elements in the ArrayList
boolean isEmpty = names.isEmpty(); // Checks if the ArrayList is empty
boolean containsAlice = names.contains("Alice"); // Checks if "Alice" is in the ArrayList

Practice with ArrayLists

Let’s practice creating, modifying, and using ArrayLists in Java. Write code snippets that demonstrate the use of ArrayList methods.

Pop Quiz

Quiz 1: Which standard Java class provides a dynamic array-like data structure that can grow or shrink in size?

  1. String
  2. Math
  3. Random
  4. ArrayList

Quiz 2: How do you create an ArrayList in Java?

  1. By using the `new ArrayList()` constructor without specifying the element type.
  2. By specifying the element type when creating the `ArrayList` (e.g., `ArrayList`).</li>
  3. By using the `ArrayList.add()` method to add elements to an existing array.
  4. By importing the `java.util.Array` class.
  5. </ol> **Quiz 3**: What method is used to add elements to an `ArrayList`?
    1. `get()`
    2. `remove()`
    3. `add()`
    4. `contains()`
    **Quiz 4**: How do you access elements in an `ArrayList` by their index?
    1. By using the `get()` method.
    2. By using the `remove()` method.
    3. By using the `add()` method.
    4. By using the `contains()` method.
    **Quiz 5**: What does the `size()` method of an `ArrayList` return?
    1. The size of the ArrayList (number of elements).
    2. The first element in the ArrayList.
    3. The last element in the ArrayList.
    4. The type of elements in the ArrayList.
    **Answers**: 1. D 2. B 3. C 4. A 5. A ### Homework 1. Create an `ArrayList` to store the names of your friends. Add at least five names to the list and print them. 2. Write a program that simulates a simple to-do list. Allow the user to add and remove tasks from the list using an `ArrayList`. Implement a menu-driven interface for the user.