Search code examples
javaarraysdebuggingequalscompareto

Having problems when comparing two arrays


The program is supposed to translate a word from American to British version. It only works for the first word but it doesn't work for the other words because it gives the else statement instead.

My code:

import java.util.Scanner;

public class BritishTranslator {

    public static void main(String[]args) {
        Scanner input = new Scanner(System.in);
        String word;

        String [] america = new String[8];
        String [] british = new String[8];

        america[0] = "attic";
        america[1] = "business suit";
        america[2] = "elevator";
        america[3] = "frenc fries";
        america[4] = "ice cream";
        america[5] = "sneakers";
        america[6] = "truck";
        america[7] = "zero";

        british[0] = "loft";
        british[1] = "lounge suit";
        british[2] = "lift";
        british[3] = "chips";
        british[4] = "ice";
        british[5] = "plimsolls";
        british[6] = "lorry";
        british[7] = "nough";

        System.out.println("Please enter an American word: ");
        word = input.nextLine();

        for (int i = 0; i < america.length; i++)

        {
            for(int j = 0; j < british.length; j++)

            {
                if (word.equals(america[i])) 

                {
                    System.out.println(america[i] + " in british is: " + british[j]);
                    System.exit(0);
                }

                else

                {
                    System.out.println("Word not found in the dictionary.");
                    System.exit(0);
                }
            }
        }
    }
}

I need help learning how to debug this code.


Solution

  • Since you are pairing your american words to your french words, you only need to loop the arrays once and if the word equals your american word then you want to print the string at the same index in both your french array and american array.

    for (int i = 0; i < america.length && i < british.length; i++)
    {
        if (word.equals(america[i])) 
        {
            System.out.println(america[i] + " in british is: " + british[i]);
            System.exit(0);
        }
    }
    
    System.out.println("Word not found in the dictionary.");