1

I want the user to input a string, then I want to check if each charachter in this string exists in an array of charachters I created. Even if it's not in the correct order.

The way I go about it is initialise the array of chars then through using the scanner have a String input from the user.

public static char[]aa={'A','C','D','E','F','G','H','I','K','L','M','N','P','Q','R','S','T','V','W','Y','U','O','B','J','Z','X'};

I created a function

private static void isValidSequence(String sequence, char[] k) {
    outter :for (int j = 0; j < sequence.length(); j++) {
        for (int i = 0; i < k.length; i++) {
            if(sequence.charAt(j) == k[i]){
                break;
            } else {     
                System.out.println("invalid"); 
                break outter;
            }
       }     
    }
}

What happens is that if for example the first letter of the the string doesn't match the first input of array it gives me an 'invalid' input. How can I go around that? and make it iterate through the whole array of characters before giving the invalid output.

1

5 Answers 5

1

An approach would be to sort your array, and then use the Binary Search Algorithm (BSA):

// sort the array once
Arrays.sort(aa);

// iterate over the input string
for(int i = 0, length = sequence.length(); i < length; i++) {
    // the java implementation of the BSA returns negative numbers for not found elements
    if(Arrays.binarySearch(aa, sequence.charAt(i)) < 0) {
        // char was not found, break loop
        return;
    }
} 

Note: If the array is not sorted / can not be sorted, then the BSA is useless and will produce undefined results.

Note 2: The BSA is faster (O(log n)) than simple iteration (O(n))

Sign up to request clarification or add additional context in comments.

Comments

0

This can also be done as below :

char[]aa={'A','C','D','E','F','G','H','I','K','L','M','N','P','Q','R','S','T','V','W','Y','U','O','B','J','Z','X'};

String s = "aStrinG";

for (char c : s.toCharArray()) {
    for (char c2 : aa) {
       if (c2 == c) {
          System.out.println("String char " + c + " exists in char array");
       }
    }
}

It produces :

String char S exists in char array
String char G exists in char array

Comments

0

Best way is to use SET instead of an Array. A set contains no duplicate elements and then simply you can use it using the method contains()

Using Java 9 (Unmodifiable Sets)

Set<Character> alphabetSet = Set.of('A', 'B', 'C');

//Another way
//Set<Character> alphabetSet = new HashSet<>(Arrays.asList('A', 'B', 'C'));

for(char c: sequence)
{
    if(alphabetSet.contains(c)){
      //do something
    }
    else{
      //do something
    }
}

Read more about Set: https://docs.oracle.com/javase/7/docs/api/java/util/Set.html

Comments

0

To directly answer your question: Solution 1: Use continue instead of break this will print "invalid" each time a character is not in k.

Solution 2: You can use a counter and increment it every time you have a character not in k, then outside the loop you will have visibility on how many invalid characters you have.

Solution 3: If you want even more detail you can have a list of characters and add each invalid character to this list. This will give you visibility on exactly what characters are invalid.

I am not sure what you are trying to do so I don't know which method is better for you, you can also use an altogether approach using streams for example.

2 Comments

I don't want it to print invalid everytime, I want to print invalid on the first character that doesn't match and exit the function. is that possible?
replace first break with continue, replace break outter with return
0

If you start using the Collection provided, you could use a Set to do your checks.

First, convert the array into the Set :

char[] array = "abcdefghijklmnopqrstuvwxyz".toCharArray();

Set<Character> setAllowed = new TreeSet<>();
for(char c : array){
    setAllowed.add(c);
}

Then, you just have to iterate and check for each character. I would add another Set to retrieve every characters not allowed, giving a better output.

Set<Character> setError = new TreeSet<>();
for(char c : s.toCharArray()){
    if(setAllowed.contains(c)){
        setError.add(c);
    }
}

Test :

public static void main(String[] args) {
    String s = "foobar123";
    char[] array = "abcdefghijklmnopqrstuvwxyz".toCharArray();

    //INIT
    Set<Character> setAllowed = new TreeSet<>();
    Set<Character> setError = new TreeSet<>();
    for(char c : array){
        setAllowed .add(c);
    }

    //RESEARCH
    for(char c : s.toCharArray()){
        if(setAllowed.contains(c)){
            setError.add(c);
        }
    }

    //OUTPUT
    System.out.println(setError);
}

[1, 2, 3]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.