Issue
I have an assignment to write a program that accepts 2 words and then returns whether they are an anagram of one another. Currently I am trying to loop through every letter of the first one, and check whether it matches with a letter in the second word. I will then compare the counter int with the total length of either word, which should be equal if they are anagrams.
I have an error where currently I get an infinite loop of counting upwards if the words are anagrams, and have a count to the number of letters in the words ending in the program not closing if not.
The assignment states "Use only the methods available in the String class. Do not use other Java library utilities", so I am unable to put the words into an array and use arrays.Sort.
import java.util.Scanner;
public class anagram {
public static void main (String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Enter two strings");
String s1 = scanner.next();
String s2 = scanner.next();
int counter = 0;
int number1 = 0;
int number2 = 0;
if(s1.length() != s2.length()) {
System.out.println("The strings are not anagrams");
} else {
for(int i = 0; i < s1.length() ; i++) {
for(int j = 0; j < s1.length() ; i++) {
// number1 = i;
// number2 = j;
if(i == s1.length()){
number1 = i - 1;
}
if(j == s2.length()){
number2 = j - 1;
}
if(s1.charAt(number1) == s2.charAt(number2)) {
counter ++ ;
System.out.println(counter);
}
}
}
System.out.println(counter);
}
System.out.println(s1 + " " + s2 + " " + counter);
}
}
Solution
Your problem lies here
for(int j = 0; j < s1.length() ; j++) { ///change i to j
You are checking n^2
times, however this could be done with only 2n
times.
- Get the occurrences of all letters from 1st String (store in array)
- Get the occurrences of all letters from 2nd String (store in array)
- Loop through both arrays concurrently and compare whether all occurrences are the same.
Your array will have 26 elements storing the occurrences of a-z
(if case is not sensitive)
Answered By - user3437460
Answer Checked By - Candace Johnson (JavaFixing Volunteer)