new to Java. I have an assignment due tonight but am stuck with what needs to be assigned within the ( )
. This is a verification of an email prefix and I am calling the prefix "example" from the method I used to get the prefix. Any help would be greatly appreciated!
public static boolean isValidPrefixChar(char b) {
return isAlphaNumeric(b) || b == '.' || b == '-' || b == '_';
This is where I am calling it:
public static boolean isValidPrefix(String str4) {
getPrefix("[email protected]");
isValidPrefixChar(???);
Please and thanks!
CodePudding user response:
tl;dr
To directly answer your question, identify the char
value of the first character of your string. Call String#charAt
. Unfortunately, that method uses annoying zero-based index counting. So the first character is counterintuitively zero rather than one.
isValidPrefixChar( prefix.charAt( 0 ) );
But… Better to avoid char
type. Pass a code point number:
isValidPrefixChar( prefix.codePointAt( 0 ) ); // Pass code point number assigned to the first (index zero) character of your input string.
char
is obsolete
The char
type has been legacy since Java 2. As a 16-bit value it is physically incapable of representing most characters. Instead use code point integer numbers.
Code points
Every known character has been assigned a specific permanent number as an identifier. This number is known as a code point.
.
= FULL STOP = 46 decimal-
= HYPHEN-MINUS = 45 decimal_
= LOW LINE = 95 decimal
Your examination of a single character would take an int
argument, as the code point.
public static boolean isValidPrefixCharacter ( int codePoint )
{
if ( ! Character.isValidCodePoint( codePoint ) ) { throw new IllegalArgumentException( "Invalid code point number passed." ); }
return
Character.isLetterOrDigit( codePoint )
|| codePoint == ".".codePointAt( 0 ) // Annoying zero-based index counting.
|| codePoint == "-".codePointAt( 0 )
|| codePoint == "_".codePointAt( 0 )
;
}
That method would be called from another method like this.
public static boolean isValidPrefix ( String possibleEmailAddress )
{
Objects.requireNonNull( possibleEmailAddress );
if ( possibleEmailAddress.isBlank() ) { throw new IllegalArgumentException( "Possible email address must have some not text, not empty string." ); }
int codePointOfFirstCharacter = possibleEmailAddress.codePointAt( 0 ); // Annoying zero-based index counting.
boolean isPrefixValid = isValidPrefixCharacter( codePointOfFirstCharacter );
return isPrefixValid;
}
Example harness code.
boolean isValid = App8.isValidPrefix( "[email protected]" );
System.out.println( "isValid = " isValid );
isValid = App8.isValidPrefix( "