Need a tad of help [modified]
-
I've got this here code I just started today for an assigment, it is all working (so I'm not asking you to do it for me :P). What this code does is it considers any @ to be a backspace and deletes the character before it. I was supposed to use indexOf() and substring() but I thought using regular expressions would be simpler, and a learning experience at the same time. I think my problem right now is that I have stared at it for too long. What I want is for the loop in main to be ran atleast once but it seems weird to have the
while(checkForError(input));
ran and then have it ran again in the methodfixErrors
. Any thoughts on what I could do to fix this would be welcome. Other comments and critiques are always welcome. Thanks, Tanner EDIT: Update at bottom.import javax.swing.*;
import java.util.regex.Pattern;
import java.util.regex.Matcher;public class bruce_tanner_A3Q3
{
public static void main(String [] args)
{
String input;
do
{
input = getString("Enter a string");
printOutput(fixErrors(input));
}while(checkForError(input));
}//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) { if(checkForError(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; } return "This string is error free"; }
}
I'm not sure whether this was a flash of brilliance or not ;) but it works. New main code:
public static void main(String [] args)
{
String input; //The main