java.lang.StringIndexOutOfBoundsException:当尝试检查单词是否为回文时,字符串索引超出范围

时间:2014-08-24 16:30:28

标签: java string

我一直在尝试编写代码来检查单词是否是第一个字母和最后一个字母相同的单词。本质上,它的代码检查Word是否是回文。

代码

import java.util.*;

public class Class1 {
   static Scanner reader = new Scanner(System.in);

   public static void main(String[] args) {
       String n = reader.next();
       boolean right = true;
       for (int i=0; i<n.length();i++)
       {
           int f = n.length()-i;
           if (n.charAt(i) != n.charAt(f -i))
           {
               right=false;
           }

       }
       System.out.println("The word is " + right);
   }    
}

我收到此错误:

TT
Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 2
at java.lang.String.charAt(Unknown Source)
at Class1.main(Class1.java:12)

谢谢。

5 个答案:

答案 0 :(得分:1)

这几乎是正确的,只有int f = n.length()-i;应为int f = n.length()-1;

n.length()-1是字符串中最后一个字符的索引。因此,f-i将是右侧的 i - 字符。

答案 1 :(得分:0)

假设一个例子,String的长度是3,当我到达2时,那么根据你f将是1

然后取这一行n.charAt(f -i)它就像charAt(1-2)所以肯定会抛出一些异常

尝试这样的事情

    int s = n.length();
    for (int i=0; i<(s/2)+1;++i) {
        if (n.charAt(i) != n.charAt(s - i - 1)){
            right=false;
        }
    }
    System.out.println("The word is " + right);

不要忘记调试代码以了解流程,只发现解决方案永远不会帮助您

答案 2 :(得分:0)

你得到的错误是索引超出范围,说明n.charAt(#)的输入参数在n的索引范围之外,它从0到n.length() - 1

然而,代码中的错误就是代码中的错误:

int f = n.length()-i; //negate i from the length
if (n.charAt(i) != n.charAt(f -i))  //negate i from the already negated length  

,修复应该是:

int f = n.length()-i-1;
if (n.charAt(i) != n.charAt(f))

答案 3 :(得分:0)

试试这个:

import java.util.*;

public class Class1 {
   static Scanner reader = new Scanner(System.in);

   public static void main(String[] args) {
       String n = reader.next();
       boolean right = true;
       int f = n.length()-1;
       for (int i=0; i<n.length();i++)
       {
           if (n.charAt(i) != n.charAt(f-i))
           {
               right=false;
           }
       }
       System.out.println("The word is " + right);
   }    
}

答案 4 :(得分:0)

要添加其他答案,您不需要遍历整个字符串。你只需要循环一半的字符串长度,看你的字符串是否是回文。

假设您正在检查女士是否是回文。你必须将女士长度的一半缩短,仅为5/2或2次。

index0 m == m index4

index1 a == a index2

所以这是稍微修改过的代码

for(int i = 0;i<n.length()/2;i++) {
    if(n.charAt(i) != n.charAt(n.length()-1-i))
    {
        right=false;
    }
}