![](/img/trans.png)
[英]Palindrome String Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: -1
[英]java.lang.StringIndexOutOfBoundsException: String index out of range when trying to check if a word is a palindrome
我一直在嘗試編寫代碼,檢查一個單詞是否是第一個字母和最后一個字母相同的單詞。 從本質上講,它是用於檢查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)
謝謝。
幾乎是對的,只是int f = n.length()-i;
應該是int f = n.length()-1;
。
n.length()-1
是字符串中最后一個字符的索引。 因此, fi
將是右邊的第i個字符。
假設舉個例子,字符串的長度為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);
不要忘記調試代碼以了解流程,只會發現解決方案永遠無法幫助您
您得到的錯誤是索引超出范圍,表明您的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))
嘗試這個:
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);
}
}
要添加其他答案,您無需遍歷整個字符串。 您只需要遍歷字符串長度的一半即可查看您的字符串是否是回文。
假設您正在檢查女士是否是回文症。 您必須循環夫人的一半長度,即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;
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.