我的程序应该在给定的输入中找到坏词,但有时我会得到一个越界错误。这个错误的原因是什么?
/* Andrew Woan - Alien Message Board Project - Period 1 */
import java.lang.Math;
import java.util.Scanner;
public class Alien {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int dollars = 0;
int qey = 0;
int carrots = 0;
System.out.println("Enter a message board post:");
String post = scan.nextLine();
String[] parts = post.split("-");
String username = parts[0]; // Alien's Username
String message = parts[1]; // Alien's Message
System.out.println(username + "-" + message);
int space = 0;
int anotherspace = message.substring(space, message.length()).indexOf(" ");
while (anotherspace != -1) {
String badword = message.substring(space, space + anotherspace);
if (badword.equals("qey")) {
qey++;
}
if (badword.equals("^^")) {
carrots++;
}
if (badword.equals("$")) {
dollars++;
}
space = +anotherspace + 1;
anotherspace = message.substring(space, message.length()).indexOf(" ");
}
char lastdollars = message.charAt(message.length() - 1);
char seconddollars = message.charAt(message.length() - 2);
char lastqey = message.charAt(message.length() - 1);
char secondqey = message.charAt(message.length() - 2);
char thirdqey = message.charAt(message.length() - 3);
char fourthqey = message.charAt(message.length() - 4);
char lastcarrots = message.charAt(message.length() - 1);
char secondcarrots = message.charAt(message.length() - 2);
char thirdcarrots = message.charAt(message.length() - 3);
if (((lastcarrots == '^') && (secondcarrots == '^') && (thirdcarrots == ' '))) {
carrots++;
}
if (((lastqey == 'y') && (secondqey == 'e') && (thirdqey == 'q') && (fourthqey == ' '))) {
qey++;
}
if (((lastdollars == '$') && (seconddollars == ' '))) {
dollars++;
}
if (qey > 0 || carrots > 0 || dollars > 0) {
System.out.println("");
System.out.println("Results:");
System.out.println("");
System.out.println("BAD");
System.out.println(username);
System.out.println("^^: " + carrots);
System.out.println("qey: " + qey);
System.out.println("$: " + dollars);
} else {
System.out.println("");
System.out.println("Results:");
System.out.println("");
System.out.println("CLEAN");
}
}
}
答案 0 :(得分:0)
我确定不知道但您是否尝试更改此行? space = + anotherspace +1;
要: 空间+ = anotherspace;
你已经用+ =增加1然后你想再做一次。这是一瞥。