Java Program Using indexOf Command

Spec Sheet

Program Title: Java Program Using indexOf Command
Purpose: To demonstrate the use of the indexOf method in Java for finding the position of a substring within a string.
Inputs: A main string and a substring entered by the user.
Outputs: The position of the first occurrence of the substring in the main string or a message if the substring is not found.
Key Features:

Pseudo Code

1. Start
2. Prompt the user to input the main string.
3. Prompt the user to input the substring to search for.
4. Use the `indexOf` method on the main string to find the substring's position.
5. If `indexOf` returns a value >= 0, display the position to the user.
6. If `indexOf` returns -1, display a "not found" message.
7. End
    

Java Code

import java.util.Scanner;

public class IndexOfExample {
    public static void main(String[] args) {
        // Create a scanner object for input
        Scanner scanner = new Scanner(System.in);

        // Step 2: Prompt the user for the main string
        System.out.println("Enter the main string:");
        String mainString = scanner.nextLine();

        // Step 3: Prompt the user for the substring
        System.out.println("Enter the substring to search for:");
        String subString = scanner.nextLine();

        // Step 4: Use the indexOf method
        int position = mainString.indexOf(subString);

        // Step 5 & 6: Check if the substring is found
        if (position >= 0) {
            System.out.println("The substring "" + subString + "" is found at position: " + position);
        } else {
            System.out.println("The substring "" + subString + "" was not found in the main string.");
        }

        // Close the scanner
        scanner.close();
    }
}
    

Sample Output

Input:
Main string: Hello, welcome to the Java world!
Substring: Java

Output:
The substring "Java" is found at position: 18

Input:
Main string: Hello, welcome to the Java world!
Substring: Python

Output:
The substring "Python" was not found in the main string.
    

Google Classroom

• Your files will be:
• PX_IndexOf_lastname.java (java program)
• PX_IndexOf_lastname.png (Screen print)
• PX_IndexOf_lastname.mp4 (video of you running your program)
• Drop off all 3 files into google classroom.