java programming question
So i was wondering...i wrote the following code using regular expressions and i wanted to know if it could be done using substring() and indexOf methods...here is my code.....
Occasionally, backspaces in text are not handled properly, and appear as part of
a String. This question asks you to handle the backspaces in a String. Your input
will be a string which contains upper and lower case letters, spaces and
punctuation, as well as the additional symbol “@”. This symbol represents that
the user typed in a backspace, and that the previous character should be
ignored. So for instance, if the user types in Hej@llo..output would be Hello
Code:
import javax.swing.*;
import java.util.regex.Pattern;
import java.util.regex.Matcher;
public class A3Q3
{
public static void main(String [] args)
{
String input; //The main method of this program only contains the input string which get's
for(input = getString("Enter a string"); checkForError(input); input = getString("Enter a string")) //it's value from the method 'getString'. It then
{ //
printOutput(fixErrors(input));
}
printOutput("This string is error free");
}
//Returns true if specified string has an error ('@' in it) and false
//if it does not.
public static boolean checkForError(String input)
{
Pattern pattern = Pattern.compile("@");
Matcher matcher = pattern.matcher(input);
return matcher.find();
}
//Prompts the user for a string with the specified input
//Returns the input string
public static String getString(String input)
{
String tempString = JOptionPane.showInputDialog(input);
return tempString;
}
//Prints the specified message
public static void printOutput(String tempString)
{
System.out.println(tempString);
}
//Fixes any errors in the input string
public static String fixErrors(String tempString)
{
Pattern pattern = Pattern.compile("[^@][@?+]");
Matcher matcher = pattern.matcher(tempString);
while(matcher.find())
{
tempString = matcher.replaceAll("");
matcher = pattern.matcher(tempString);
}
pattern = Pattern.compile("@"); //This block gets rid of any extra @'s left over.
matcher = pattern.matcher(tempString);
tempString = matcher.replaceAll("");
return tempString;
}
}