We read your photo as:

Program to count vowels and consonants in a string in Java

Computer Science

ScanSolve AI Answer

Here are the solutions to your assignment questions.

1. Program to count vowels and consonants in a string in Java

public class VowelConsonantCounter {

    public static void main(String[] args) {
        String text = "Hello World";
        countVowelsAndConsonants(text);

        text = "Java Programming";
        countVowelsAndConsonants(text);
    }

    public static void countVowelsAndConsonants(String str) {
        int vowels = 0;
        int consonants = 0;

        // Convert the string to lowercase to handle both cases easily
        str = str.toLowerCase();

        for (int i = 0; i < str.length(); i++) {
            char ch = str.charAt(i);

            // Check if the character is an alphabet
            if (ch >= 'a' && ch <= 'z') {
                if (ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u') {
                    vowels++;
                } else {
                    consonants++;
                }
            }
        }
        System.out.println("String: \"" + str + "\"");
        System.out.println("Number of vowels: " + vowels);
        System.out.println("Number of consonants: " + consonants);
        System.out.println();
    }
}

Explanation:
The countVowelsAndConsonants method iterates through each character of the input string. It first converts the string to lowercase to simplify vowel checking. For each character, it checks if it's an alphabet. If it is, it then determines if it's a vowel (a, e, i, o, u) or a consonant and increments the respective counter. Finally, it prints the total counts.

2. Implement a method that reverses a String using StringBuilder in Java

public class StringReverser {

    public static void main(String[] args) {
        String originalString1 = "Java";
        String reversedString1 = reverseString(originalString1);
        System.out.println("Original String: " + originalString1);
        System.out.println("Reversed String: " + reversedString1);
        System.out.println();

        String originalString2 = "Programming";
        String reversedString2 = reverseString(originalString2);
        System.out.println("Original String: " + originalString2);
        System.out.println("Reversed String: " + reversedString2);
    }

    public static String reverseString(String str) {
        // Create a StringBuilder object with the input string
        StringBuilder sb = new StringBuilder(str);

        // Use the reverse() method of StringBuilder
        sb.reverse();

        // Convert the StringBuilder back to a String and return it
        return sb.toString();
    }
}

Explanation:
The reverseString method takes a String as input. It creates a StringBuilder object initialized with this string. The StringBuilder class has a built-in reverse() method, which efficiently reverses the sequence of characters. Finally, toString() is called on the StringBuilder object to convert the reversed sequence back into a String, which is then returned.

3. Create a simple login system that reads usernames/passwords from a file in Java

First, create a file named credentials.txt in the same directory as your Java code, with content like this:

user1:pass1
admin:admin123
test:password
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;

public class LoginSystem {

    private static final String CREDENTIALS_FILE = "credentials.txt";
    private Map<String, String> users;

    public LoginSystem() {
        users = new HashMap<>();
        loadCredentials();
    }

    private void loadCredentials() {
        try (BufferedReader reader = new BufferedReader(new FileReader(CREDENTIALS_FILE))) {
            String line;
            while ((line = reader.readLine()) != null) {
                String[] parts = line.split(":");
                if (parts.length == 2) {
                    users.put(parts[0], parts[1]);
                }
            }
        } catch (IOException e) {
            System.err.println("Error loading credentials file: " + e.getMessage());
            System.err.println("Please ensure '" + CREDENTIALS_FILE + "' exists and is correctly formatted.");
        }
    }

    public boolean authenticate(String username, String password) {
        return users.containsKey(username) && users.get(username).equals(password);
    }

    public static void main(String[] args) {
        LoginSystem loginSystem = new LoginSystem();
        Scanner scanner = new Scanner(System.in);

        System.out.print("Enter username: ");
        String username = scanner.nextLine();

        System.out.print("Enter password: ");
        String password = scanner.nextLine();

        if (loginSystem.authenticate(username, password)) {
            System.out.println("Login successful! Welcome, " + username + ".");
        } else {
            System.out.println("Login failed. Invalid username or password.");
        }

        scanner.close();
    }
}

Explanation:
The LoginSystem class reads usernames and passwords from a file named credentials.txt into a HashMap during initialization. Each line in the file should be in the format username:password. The authenticate method checks if the provided username exists in the map and if its corresponding password matches the input password. The main method prompts the user for credentials and then uses the authenticate method to verify them, printing a success or failure message. Error handling for file reading is included.

4. Differentiate between Getters and Setters method in Java with example of each

Getters and Setters are special methods used in Java to access and modify the values of private instance variables, respectively. They are fundamental to the concept of encapsulation, which is one of the four pillars of Object-Oriented Programming (OOP). Encapsulation ensures that the internal state of an object is hidden from the outside world, and access to it is controlled through public methods.

  • Getter Method (Accessor Method): A getter method is used to retrieve the value of a private field. It typically starts with get followed by the field name (e.g., getName()). It takes no arguments and returns the value of the field.

  • Setter Method (Mutator Method): A setter method is used to modify or set the value of a private field. It typically starts with set followed by the field name (e.g., setName()). It takes one argument, which is the new value for the field, and usually has a void return type. Setters can include validation logic to ensure data integrity.

Example:

public class Student {
    private String name; // Private instance variable
    private int age;     // Private instance variable

    // Getter for name
    public String getName() {
        return name;
    }

    // Setter for name
    public void setName(String name) {
        // Optional: Add validation logic here
        if (name != null && !name.trim().isEmpty()) {
            this.name = name;
        } else {
            System.out.println("Name cannot be empty.");
        }
    }

    // Getter for age
    public int getAge() {
        return age;
    }

    // Setter for age
    public void setAge(int age) {
        // Optional: Add validation logic here
        if (age > 0 && age < 120) {
            this.age = age;
        } else {
            System.out.println("Invalid age provided.");
        }
    }

    public static void main(String[] args) {
        Student student = new Student();

        // Using setter methods to set values
        student.setName("Alice");
        student.setAge(20);

        // Using getter methods to retrieve values
        System.out.println("Student Name: " + student.getName()); // Output: Student Name: Alice
        System.out.println("Student Age: " + student.getAge());   // Output: Student Age: 20

        // Demonstrate validation
        student.setAge(-5); // Output: Invalid age provided.
        student.setName(""); // Output: Name cannot be empty.
    }
}

Explanation:
In the Student class, name and age are private, meaning they cannot be directly accessed from outside the class. getName() and getAge() are getter methods that provide read-only access to these fields. setName() and setAge() are setter methods that allow controlled modification of these fields. The setters include basic validation to ensure that the name is not empty and age is within a reasonable range, demonstrating how encapsulation helps maintain data integrity.

Was this helpful?

Still stuck on this one?

Ask a follow-up, and the answer starts from this question.

Got a different question?Ask your own question