0

My main goal is to get a value of -1 for indexOf every time a letter is not found in the word it is being searched for in. I can use this value to determine if the words are anagrams or not. The issue, however, is that I am continually getting 0 for indexOf. Shouldn't I be getting -1 if the letters are completely different?.

import java.lang.*;
import java.io.*;
import java.util.*;


public class anagram
{


    public static void main(String args[])
    {

        Scanner kbReader = new Scanner(System.in);
        System.out.println("Enter first word");
        String a = kbReader.next();
        System.out.println("Enter second word");
        String b = kbReader.next(); ///User inputs 2 strings, a and b
        a = a.toLowerCase();
        b = b.toLowerCase();

        int numA = a.length();
        int numB = b.length();

        if (numA != numB)
           System.out.println("NOT AN ANAGRAM"); 



        for(int i = 0;i < numA; i++) ///continues until all letters are used
        {
            String letter = b.substring(i,i++);
            int checker = a.indexOf(letter);///checks word a for every letter of b

            System.out.println(checker); ///always get 0 for this value, why never -1?



       }
   }


}
  • I'm not sure about "always zero" but `indexOf()` returns the index of the first letter. I'm not sure what is you are trying to achieve with it. (You're also incrementing i++ too many times.) – markspace Nov 14 '18 at 04:29
  • OK, you're using the `String` version of `indexOf`. `substring(i,i++)` always returns an empty string, and the empty string always matches an empty string at the very beginning of any string. So the empty string `letter` is the problem, and the root of that is your index values. – markspace Nov 14 '18 at 04:36

2 Answers2

1

change to

String letter = b.substring(i,i + 1);

See also post increment operator java

By the way, Strings of equal size does not mean that they are Anagrams

Scary Wombat
  • 44,617
  • 6
  • 35
  • 64
  • *Strings of equal size does not mean that they are Anagrams* - yes, but unequal size strings do mean that they are definitely not anagrams, which is what OP has done – Kartik Nov 14 '18 at 04:41
  • @Kartik - well maybe that is what he is heading towards eh. – Scary Wombat Nov 14 '18 at 04:42
  • but he did not break when strings are unequal, and that code is not perfect, just want to give heads up to OP – Ryuzaki L Nov 14 '18 at 04:43
  • Kartlik is right, Deadpool is right - now just upvote me. – Scary Wombat Nov 14 '18 at 04:46
  • lol yeah, would like to see the completed code.. just put an `else` right before the for-loop to solve the breaking problem :D – Kartik Nov 14 '18 at 04:48
  • @Kartik I am now getting the correct value for indexOf, and also added an else statement. One issue left, however, how do I break out of the for loop to state whether it is an anagram or not? Edit: I cant post the code in a comment, first time using stack, ima figure this out one sec... – Hamza Khan Nov 14 '18 at 05:36
0

Answering to why you cannot get any thing other that 0 from indexOf():

In this statement, String letter = b.substring(i,i++); lets say you are in second iteration (that is i = 2) in the for loop. You have used a post increment operator, that means first the statement is executed and then the value is incremented.

In that case b.substring(i,i++); resolves to b.substring(2,2); and you get String letter = ""

According to implementation of indexOf(), index of "" in any string is returned as 0 and this is where purpose of your logic gets defeated.

Just for understanding purpose I will paste the implemantation of indexOf() from String.java class:

/**
 * Code shared by String and StringBuffer to do searches. The
 * source is the character array being searched, and the target
 * is the string being searched for.
 *
 * @param   source       the characters being searched.
 * @param   sourceOffset offset of the source string.
 * @param   sourceCount  count of the source string.
 * @param   target       the characters being searched for.
 * @param   targetOffset offset of the target string.
 * @param   targetCount  count of the target string.
 * @param   fromIndex    the index to begin searching from.
 */
static int indexOf(char[] source, int sourceOffset, int sourceCount,
        char[] target, int targetOffset, int targetCount,
        int fromIndex) {
    if (fromIndex >= sourceCount) {
        return (targetCount == 0 ? sourceCount : -1);
    }
    if (fromIndex < 0) {
        fromIndex = 0;
    }
    if (targetCount == 0) {
        return fromIndex;
    }

    char first = target[targetOffset];
    int max = sourceOffset + (sourceCount - targetCount);

    for (int i = sourceOffset + fromIndex; i <= max; i++) {
        /* Look for first character. */
        if (source[i] != first) {
            while (++i <= max && source[i] != first);
        }

        /* Found first character, now look at the rest of v2 */
        if (i <= max) {
            int j = i + 1;
            int end = j + targetCount - 1;
            for (int k = targetOffset + 1; j < end && source[j]
                    == target[k]; j++, k++);

            if (j == end) {
                /* Found whole string. */
                return i - sourceOffset;
            }
        }
    }
    return -1;
}

Here targetCount is 0 and you get 0 value returned in your code.

abj1305
  • 635
  • 9
  • 21