Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Please help with these two questions! Thanks! Fill in the code for the following

ID: 3623447 • Letter: P

Question

Please help with these two questions! Thanks!


Fill in the code for the following class methods:

a. The following method returns the position of the first occurrence of a given character in a given string. The position starts from 0 for the first character in the string. The method should return -1 if the character does not appear in the string. For example, the call indexOf('t',"iteration") would return 1, and the call indexOf('s',"iteration") would return -1. (You are not allowed to use the String indexOf method.)


public static int indexOf(char c, String str)
{
// fill this in
}



b. Given two String parameters, the following method returns true if they are the same string of characters, and false otherwise. Note: You cannot use the equals String method; in other words, you actually have to write the code that compares the two strings character by character.


public static boolean stringsAreEqual(String s1, String s2)
{
// fill this in
}

Explanation / Answer

Please rate: I added notes in the code for your convenience...If you have any questions pliz feel free to ask

********************************************************

public class Main {

    public static void main(String[] args) {
        String first = "interesting";
        String second = "interesting";
        char ch = 'w';

        System.out.println(indexOf(ch, first));
        System.out.println(stringsAreEqual(first, second));
    }

    /* The method returns 1 if a character appears in the string, otherwise returns -1
     *
     * The for loop will loop from 0 to string length -1 times.
     * The loop will break immediately when it finds a character match if not
     * it will exit the loop after it loops completely and prints -1
     */
    public static int indexOf(char c, String str) {

        for (int i = 0; i < str.length(); i++) {
            char a = str.charAt(i);
            if (a == c) {
                return 1;
            }
        }
        return -1;
    }

    /* The method returns true if two strings are the same and false otherwise.
     *
     * Checks if the two strings are of the same length if not it prints false immediately
     * If the strings are of the same length, it will check character by character if they are the same
     */
    public static boolean stringsAreEqual(String s1, String s2) {

        if (s1.length() == s2.length()) {

            if (s1.compareTo(s2) == 0) {
                return true;
            } else {
                return false;
            }
        } else {
            return false;
        }
    }
}