1

My program is meant to return a reversed version of whatever string the user inputs, but it should also report bad input if the string contains any symbols. I cannot seem to find a way to do this. By the way the program comes with an IO.java module. Here is my code

public class ReverseWords{
public static void main(String [ ] args){
    String word= IO.readString();
       if(word.contains("[\\!\\*\\@\\#\\-\\+\\.\\^\\:\\.\\]")){
          IO.reportBadInput();}

   word = new StringBuffer(word).reverse().toString();
   IO.outputStringAnswer(word);

  }
  }
lazepanda
  • 11
  • 4
  • 3
    [`contains` expects a literal string, not a regex.](http://stackoverflow.com/questions/15130309/how-to-use-regex-in-string-contains-method-in-java) – resueman Jun 22 '16 at 17:32
  • could you expand a bit more? I am fairly new to java – lazepanda Jun 22 '16 at 17:41
  • The `String` you passed to `contains` is a regular expression. However, `contains` won't treat it as a one; it will search for the exact characters you specified. So unless the string contains `[\!\*\@\#\-\+\.\^\:\.\]` it won't match, even if it contains one of those characters. You should use the solution proposed in the link I posted above. – resueman Jun 22 '16 at 17:49
  • I looked at the link you posted but it seems that the answer pertains to cases where you would want to find certain words, but ommit the symbol. Rather then finding the symbols themselves and reporting bad input. – lazepanda Jun 22 '16 at 18:07

2 Answers2

1

Put the following code in main method and test it .

Pattern p = Pattern.compile("[^a-z0-9 ]", Pattern.CASE_INSENSITIVE);
    Scanner sc = new Scanner(System.in);
    System.out.println("Pleease enter a String ::");
    String str = sc.next();
    Matcher m = p.matcher(str);
    if (m.find()){
        System.out.println("String Contains Special Chars");
    }else{

        System.out.println("It is String ");
        System.out.println(new StringBuilder(str).reverse().toString());
    }
       sc.close();
Raju
  • 143
  • 5
0

You can use regexp to detect non-alphanumeric symbols

Pattern pattern = Pattern.compile("[^a-zA-Z0-9]");
Boolean hasNonAlphaNumeric = p.matcher(s).find();

Or you can use Apache's StringUtils class and its method

boolean StringUtils.isAlphanumeric(String string)
Mikhail Chibel
  • 1,865
  • 1
  • 22
  • 34