java - 比较两个数组时出现问题
问题描述
该程序应该将一个单词从美国翻译成英国版本。它仅适用于第一个单词,但不适用于其他单词,因为它给出了 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);
}
}
}
}
}
我需要帮助学习如何调试此代码。
解决方案
你只需要遍历美国数组,如果你发现单词在英国数组中查看相同的索引。和其他的循环
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
}
推荐阅读
- visual-studio - F12 仅将我带到元数据
- python - Python pandas中Excel索引匹配的等价物
- mysql - 简化mysql联合查询
- sql-server - 如何在 GROUP BY 语句中返回零计数
- android - 领域迁移 android addRealmObjectField
- mysql - MySQL SELECT 查询在哪里查找不在相关表中的记录
- r - 如何使用 R 中的 ggplot 在一个绘图上绘制两个不同的观察结果?
- bash - 当只有链接可用时如何获取文件的总文件大小
- c++ - DXRSDK_v0.09.01 无法在 Visual Studio 2017 上运行
- php - 想要获取数组值