我在这行代码中遇到错误:while(s.charAt(i - 1)!=' \ 0')。 我尝试使用开关比较输入字符串,这里是整个代码:
public static int Main()
{
String s = new String(new char[20]);
byte c;
int state = 0;
int i = 0;
System.out.print("\n Enter a string:");
s = new Scanner(System.in).nextLine();
while (s.charAt(i - 1) != '\0')
{
char result = s.charAt(i);
System.out.println(result);
switch (state)
{
case 0:
c = (byte) s.charAt(i++);
if (c == (byte)'a')
{
state = 1;
}
else if (c == (byte)'b')
{
state = 2;
}
else
{
state = 6;
}
break;
case 1:
c = (byte) s.charAt(i++);
if (c == (byte)'a')
{
state = 3;
}
else if (c == (byte)'b')
{
state = 4;
}
else
{
state = 6;
}
break;
case 2:
c = (byte) s.charAt(i++);
if (c == (byte)'a')
{
state = 6;
}
else if (c == (byte)'b')
{
state = 2;
}
else
{
state = 6;
}
break;
case 3:
c = (byte) s.charAt(i++);
if (c == (byte)'a')
{
state = 3;
}
else if (c == (byte)'b')
{
state = 2;
}
else
{
state = 6;
}
break;
case 4:
c = (byte) s.charAt(i++);
if (c == (byte)'a')
{
state = 6;
}
else if (c == (byte)'b')
{
state = 5;
}
else
{
state = 6;
}
break;
case 5:
c = (byte) s.charAt(i++);
if (c == (byte)'a')
{
state = 6;
}
else if (c == (byte)'b')
{
state = 2;
}
else
{
state = 6;
}
break;
case 6:
System.out.printf("\n %s is not recognised.",s);
System.exit(0);
}
}
if (state == 1)
{
System.out.printf("\n %s is accepted under rule 'a'",s);
}
else if ((state == 2) || (state == 4))
{
System.out.printf("\n %s is accepted under rule 'a*b+'",s);
}
else if (state == 5)
{
System.out.printf("\n %s is accepted under rule 'abb'",s);
}
return 0;
}
它表示字符串索引超出范围。我也尝试显示字符(i)它显示正确的字符串,但我不知道为什么我有这个错误
答案 0 :(得分:0)
您正在使用int i = 0;
,然后检查while (s.charAt(i-1) != '\0')
。当您将i
设置为0
时,i-1
将为-1
和StringIndexOutOfBoundsException
会发生。所以使用int i = 1;
或while (s.charAt(i) != '\0')