gpt4 book ai didi

java - 单词数组,然后嵌套 for 循环来检查字符

转载 作者:行者123 更新时间:2023-12-01 13:01:45 25 4
gpt4 key购买 nike

嘿伙计们,我是java编程的新手,我试图找出为什么我的第二个循环中的字符串超出范围。我正在尝试创建一个拼写检查器,我不确定我是否做得不太正确。我试图检查一个句子的单词并将其与其他单词数组进行比较,并对每个字符进行字符化,直到 toCheck 的长度结束,但不起作用:\

任何帮助将不胜感激!预先感谢您

    public static String suggestions (String toCheck, String [] words, Scanner kb)
{//start
int length=toCheck.length(),total=0, count = 0;
for(int x = 0;x<words.length;x++)
{
if(words[x].charAt(0)==(toCheck.charAt(0)))
for(int j = 0;j<length-1;j++)
{
if(toCheck.charAt(j)==words[x].charAt(j))
count++;

}
if(count>=((words[x].length())/2))
total++;}

System.out.println(total);
//System.out.printf("Not found - %s",toCheck);
//System.out.println("\nChoices 1 leave as it 2. Type replacement 3 Pick one " + Arrays.toString(suggest));
return toCheck;

}//end of suggestions

显示错误消息

Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 3
at java.lang.String.charAt(String.java:686)
at CSCD210HW4.suggestions(CSCD210HW4.java:59)
at CSCD210HW4.main(CSCD210HW4.java:44)

最佳答案

为什么不使用compareTo而不是手动检查不同的字符。会更容易。

例如

  count = Math.abs(words[x].compareTo(toCheck)); 
//It will return the difference of character in both string.
// Suppose words[x] = "abc" and toCheck = "adc" then count will be 1.

关于java - 单词数组,然后嵌套 for 循环来检查字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23469116/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com