Why is Arrays.equals returning false?

113 views Asked by At

EDIT: Thanks to everyone who commented, you've helped me figure it out. So I'm comparing the two arrays before I remove all of the blank spaces by converting it to a string. So either I'll have to copy array to a new array without the blank spaces, or compare the strings instead of comparing the arrays.

—————————————————————————

The problem is even when the input is a pangram, the Boolean still returns false.

//Miller
//2023-12-21
//PangramTest

import java.util.Scanner;
import java.util.Arrays;

public class PangramTest {
    public static void main (String[] args){
        //Alphabet template
        char[] alphabetArray = {97,98,99,100,101,102,103,104,105,106,107,108,109,
                            110,111,112,113,114,115,116,117,118,119,120,121,122};
        String alphabetStr = new String(alphabetArray);
        
        //User input
        Scanner input = new Scanner(System.in);
        String str = input.nextLine();
        
        //Call pangram method using user input
        char[] finalStrArray = pangram(str);
        
        //Convert char array to string and remove blank spaces
        String finalStr = new String(finalStrArray).replaceAll(" ", "");
        
        System.out.println("Alphabet: " + alphabetStr);
        System.out.println("Sentence: " + finalStr);
        System.out.println("Pangram?: " + Arrays.equals(alphabetArray, finalStrArray));
    }
    
    
    public static char[] pangram(String str){
        char[] strArray = str.toLowerCase().toCharArray();
        
        //Removes all duplacite lettes from char array
        for(int i = 0; i < strArray.length; i++){
            for(int x = i + 1; x < strArray.length; x++){
                if(strArray[i] == strArray[x]) 
                    strArray[x] = ' ';
            }
        }
        
        //Sort array alphabeticly then return
        Arrays.sort(strArray);
        return strArray;
    }
}

I'm trying to compare two char arrays using Arrays.equals(); to determine whether or not the given string is a pangram. The user inputs a string, I change the string into a char array then sort it alphabetically and remove all blank space and duplicate letters. Then I compare the input array with a char array of the alphabet Even when the input string is a pangram, such as "The quick brown fox jumps over the lazy dog", the boolean still returns false.

0

There are 0 answers