Skip to main content
edited tags
Link
200_success
  • 145.6k
  • 22
  • 191
  • 481
Source Link

Checking if a string matches an array of valid characters

I am wondering what a better solution would be for this bit of code:

public static void main( String[] args )
{
    String name = "hello, ddd";

    boolean[] success = new boolean[ name.length() ];
    for( char character: VALID_CHARS ) {
        for( int index = 0; index < name.length(); index ++ ) {
            if( name.charAt( index ) == character ) {
                success[ index ] = true;
            }
        }
    }

    boolean failed = false;
    for( boolean b: success ) {
        if( ! b ) {
            failed = true;
        }
    }

    System.out.println( "You" + ( failed ? " failed": " succeeded" ) + "." );
}

I have an array of valid characters that can be used for a name object, I want to check if each index of the string is valid, if each index is valid return true, otherwise return false. Any help / guidance is appreciated!