[英]Java consecutive checker
I am trying to write a code which checks if a string or either letters or numbers is consecutive, however every time I run the program it gives me nothing back but an error: java.lang.ArrayIndexOutOfBoundsException: 4
. 我正在尝试编写一个代码,该代码检查字符串或字母或数字是否连续,但是,每次运行该程序时,它只会返回一个错误: java.lang.ArrayIndexOutOfBoundsException: 4
。
Im not sure what the problem is as I am fairly new to programming, any help would be greatly appreciated. 我不确定是什么问题,因为我是编程的新手,将不胜感激。
public class Question1
{
public static void main(String[] args)
{
java.util.Scanner keyboardReader = new java.util.Scanner(System.in);
String userInput = keyboardReader.nextLine();
isConsecutive(userInput);
}
public static void isConsecutive(String s)
{
s = s.toUpperCase();
int x = 0;
char [] inputArray = s.toCharArray();
for (int i=0; i<s.length(); i++)
{
if (Math.abs(inputArray[i] - inputArray[(i+1)]) != 1)
{
System.out.println("false");
}
else
{
x++;
}
}
System.out.println(x);
}
}
You have to do: 你必须做:
for (int i=0; i < s.length() - 1; i++)
because when the loop is at the last execution step and calculates 因为当循环在最后一个执行步骤并进行计算时
Math.abs(inputArray[i] - inputArray[(i+1)]) != 1
, Math.abs(inputArray[i] - inputArray[(i+1)]) != 1
,
then inputArray[i+1]
refers to an element which is out of the array bounds. 然后, inputArray[i+1]
引用超出数组范围的元素。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.