索引帮助 Java



我想知道是否有办法获取索引,让我给你看一个例子。

String[] names = {"Daniel", "Lewis", "Sarah", "John"};
   String cmd = input.nextLine();
  String CMD[] = cmd.split(" ");

  if (CMD[0].equalsIgnoreCase("my name is") && CMD[1].equalsIgnoreCase(accountIndex[0])){
     System.out.println("My name is Daniel!");
  } else if (CMD[0].equalsIgnoreCase("my name is") && CMD[1].equalsIgnoreCase(accountIndex[1])) {
     System.out.println("My name is Lewis!");
  } else if (CMD[0].equalsIgnoreCase("my name is") && CMD[1].equalsIgnoreCase(accountIndex[2])) {
     System.out.println("My name is Sarah!");
  } else if (CMD[0].equalsIgnoreCase("my name is") && CMD[1].equalsIgnoreCase(accountIndex[3])) {
     System.out.println("My name is John!");
  }

有没有比嵌套 if 语句更简单的方法?

请注意,我只想在表内使用名称,所以我不能只使一个名为 myName 的字符串等于 CMD[1]。

我想这有点像用户名数据库,如果您的用户名不存在,您将无法登录。

我想要这样,但没有嵌套 if 语句的负载,并且名称 Array 将是本实例中的数据库。

你可以做

List<String> names = Arrays.asList("Daniel", "Lewis", "Sarah", "John");
if (names.contains(CMD[3]) {
    System.out.println("My name is " + CMD[0]);
} else {
    // not found...
}

你正在一个空格上分裂,所以

CMD[0].equalsIgnoreCase("my name is")

永远不会评估为真实。

为什么要测试"my name is "?只需捕获第四个单词,如果这是您正在使用的格式:CMD[3]

为了避免这些 if-else-if-else,请将名称放入 Map 中,其中键是名称,并且值始终null

然后根据密钥测试名称:

if(mapOfNames.containsKey(CMD[3]))

您可以尝试for循环:

for (int i = 0; i < names.length(); i++) {
    if (CMD[3].equalsIgnoreCase(accountIndex[i])) {
        System.out.println("My name is " + names[i] + "!");
        break;
    }
}

运行cmd.split()将拆分数组,为您提供一个数组:{"my", "name", "is", "some_name"} .这意味着您要检查的名称将在数组中的第四个元素处给出,因此索引[3]

String[] names = {"Daniel", "Lewis", "Sarah", "John"};
String cmd = input.nextLine();
String CMD[] = cmd.split(" ");
// Initial check to see if my name is exists.
if(cmd.subtstring(0, 10).equalsIgnoreCase("my name is") && cmd.length > 3)
{
    // This loop is better than checking each individual case because it allows you to dynamically add elements to your names array
    for(int i = 0; i < names.length; i++)
    {
        // Must start at the fourth element since my, name, and is will be the 0-2 elements.
        if(CMD[3].equalsIgnoreCase(names[i]))
        {
            System.out.println("My name is "+names[i]+"!");
            break;
        }
    }
}

您可以将有效的用户名存储在 TreesSet 中,然后当用户输入名称时,您可以查找 TreeSet 以测试给定名称是否为有效名称。

TreeSet<String> validNames = new TreeSet<String>();
validNames.add("John");
validNames.add("Mary");
.....
.....
// For searching
if(validNames.contains(CMD[0]))
{
 // name exists
}
else{
   // invalid name
}

注意:您可以将名称存储在任何可搜索的集合中(HashMaps也是这种情况的不错选择。这只是一个指针,您需要深入挖掘以找到适合您需求的数据结构。有关更多信息,您可以参考以下链接:

树集

哈希地图

您可以将数组转换为列表,然后使用contains方法在列表中搜索名称:

if(Arrays.asList(names).contains(CMD[3]))
    System.out.println("My name is " + CMD[3] + "!");

最新更新