【问题标题】:How to check two indices of a string to see if the characters match如何检查字符串的两个索引以查看字符是否匹配
【发布时间】:2018-09-26 00:43:06
【问题描述】:

我正在尝试检查两个不同的索引以查看它们是否匹配。在我的情况下,我正在检查索引 3 和 4。确定它们是否匹配没有问题,但是如果我的字符串太短并且在索引 3 或 4 处没有字符,我的程序就会出错。

这是我的代码的副本。谁能告诉我我做错了什么?

/**
 * Checks the characters in a String at indices 3 and 4 to see if those characters match
 * @param input String to check
 * @return "MATCH" if String's indices 3 and 4 have the same letter, "NO MATCH" if String's
 * indices 3 and 4 do not have the same letter, "N/A" if the String is too short to have a letter at index 3 or index 4
 */
private static String method4(String input) {

    Scanner scan = new Scanner(System.in);

    System.out.println("What is your word? ");
    input = scan.nextLine();
    int len = input.length();

    if (len < 4) {
        System.out.println("N/A");
    }
    else{
        char char1 = input.charAt(3);
        char char2 = input.charAt(4);
        if ((char1) == (char2)) {
        System.out.println("MATCH");
    }}
    else
    System.out.println("NO MATCH");

【问题讨论】:

  • 我建议进行编辑以将java 标签添加到您的问题中。另外,不要说“我的程序出错了”,而是尝试查找错误消息,检查它的内容,然后将其包含在您的帖子中,以便其他人了解问题所在。

标签: java string charat


【解决方案1】:

您使用charAt 的方法是像数组一样从零开始。

if (len < 4) {
    System.out.println("N/A");
}

仅确保字符串至少有 4 个字符,第 4 个字符的索引为 3。

"abcd".charAt(3) == 'd'

所以当字符串正好有4个字符时input.charAt(4)会抛出异常。

【讨论】:

    【解决方案2】:
    try (Scanner scan = new Scanner(System.in)) {
        System.out.println("What is your word? ");
        String str = scan.nextLine();
        int len = str.length();
    
        if (len < 5)
            System.out.println("N/A");
        else if (str.charAt(3) == str.charAt(4))
            System.out.println("MATCH");
        else
            System.out.println("NO MATCH");
    }
    

    正如其他帖子中提到的:

    String str = "abcd";
    str.legnth == 4
    str.charAt(3) == 'd' // zero-based
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-11-13
      • 1970-01-01
      • 2015-12-30
      • 2010-12-08
      • 2021-01-11
      相关资源
      最近更新 更多