I am attempting to create a method in Java which will recognize non alphanumeric symbols in a line of text and remove them. However, I am limited in the tools that I can use. I have to use a loop and a scanner to read through the text, and only using the charAt and substring methods to remove the offending characters. Here is the code that I came up with
public String sanitize2(){
Scanner sanitizer = new Scanner(input.getText());
String toBeSanitized = sanitizer.nextLine();
int length = toBeSanitized.length();
for (int i=0;i < toBeSanitized.length(); i++){
if ((toBeSanitized.charAt(i) >= 'a' && toBeSanitized.charAt(i) <= 'z') ||
(toBeSanitized.charAt(i) >= 'A' && toBeSanitized.charAt(i) <= 'Z') ||
(toBeSanitized.charAt(i) >= '0' && toBeSanitized.charAt(i) <= '9'))
{
toBeSanitized = toBeSanitized.substring(0,i) + toBeSanitized.substring(i+1);
}
}
input.setText(toBeSanitized);
return toBeSanitized;
}
However it completely gives the wrong answer when i insert text into the input field. Can anyone shed light on what i'm doing wrong here?