报告不良输入,如果字符串包含字母和空格以外的其他内容



我的程序旨在返回用户输入的任何字符串的反向版本,但是如果字符串包含任何符号,它也应报告不良输入。我似乎找不到这样做的方法。顺便说一句,该程序带有io.java模块。这是我的代码

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);
  }
  }

将以下代码放在主方法中并对其进行测试。

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();

您可以使用Regexp检测非alphanumeric符号

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

或者您可以使用Apache的Stringutils类及其方法

boolean StringUtils.isAlphanumeric(String string)

相关内容

最新更新