I’m making a cryptography/cryptanalysis program using java as a homework for my master. Anyway, i use a method to delete the uselless whitespaces and make the String i display to the JTextArea proper. This method is great for small texts but it gives me a StringIndexOutOfBoundsException when i use bigger texts (loaded from a .txt file). Can anyone help?
Thanks in advance.
This is the method:
public void Data(String s) {
System.out.print("Analysis" + "\n" + s);
jTextArea1.setText(s);
StringBuilder buf = new StringBuilder();
for (int i = 0; i < s.length(); i++) {
if (!Character.isWhitespace(s.charAt(i))) {
buf.append(s.charAt(i));
} else if (Character.isWhitespace(s.charAt(i)) && !Character.isWhitespace(s.charAt(i + 1))) {
buf.append(s.charAt(i));
}
}
System.out.println(buf.toString() + "\n" + "from buf");
jTextArea1.setText(buf.toString());
}
You are going up to
s.length()in the for loop but accessings.charAt(i + 1)in the second if statement. Try to only go up tos.length() - 1:And then check the last character afterwards.