首页 > 解决方案 > 比较两个数组时出现问题

问题描述

该程序应该将一个单词从美国翻译成英国版本。它仅适用于第一个单词,但不适用于其他单词,因为它给出了 else 语句。

我的代码:

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);
                }
            }
        }
    }
}

我需要帮助学习如何调试此代码。

标签: javaarraysdebuggingequalscompareto

解决方案


你只需要遍历美国数组,如果你发现单词在英国数组中查看相同的索引。和其他的循环

    for (int i = 0; i < america.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.");
    System.exit(0); // you dont need this as well

}

推荐阅读