Search code examples
javaconditional-statementscomparecharacter

Checking if string contains unusual characters using ".contain"


I'm trying to create a simple program in JAVA to identify if a user input string contains a special character for example "!", and if it does it appends it to arrayList1 if it does not it appends the string to arrayList2

i've been told that i can use the new .contain method to determine if the user string input contains a pre defined unusual symbol.

i've been putting in example inputs like he!!o but it isn't read as a string with a special character.

here's the code snippet

public static void main(String[] args) {
    
    Scanner input= new Scanner(System.in);
    String answer;
    ArrayList<String> arrayList1 = new ArrayList<>();
    ArrayList<String> arrayList2 = new ArrayList<>();
    
    //do {  
        System.out.println("enter passswords");
        
        answer= input.nextLine();
        String SimpleSymbol="!@#$%^&*()_+";
        if(answer.contains(SimpleSymbol)) {
            arrayList2.add(answer);
            System.out.println("with special numbers" + arrayList2);         
        } else {
            arrayList1.add(answer);
            System.out.println("without SP" + password);
        }
    }
}

Solution

  • You can use regex match for pattern match.

    Try below code:

    import java.util.ArrayList;
    import java.util.Scanner;
    import java.util.regex.Pattern;
        public static void main(String[] args) {
    
            Scanner input = new Scanner(System.in);
            String answer;
            ArrayList<String> arrayList1 = new ArrayList<>();
            ArrayList<String> arrayList2 = new ArrayList<>();
    
            //do {
            System.out.println("enter passswords");
    
            answer = input.nextLine();
            Pattern pattern
                    = Pattern.compile("[@_!#$%^&*()<>?/|}{~:]");
            if (pattern.matcher(answer).find()) {
                arrayList2.add(answer);
                System.out.println("with special numbers" + arrayList2);
            } else {
                arrayList1.add(answer);
                System.out.println("without SP" + answer);
            }
        }
    

    References:

    1. Pattern Matching
    2. How to use String.contains() method