Usa regex para este problema.
Código Java:
Ver originalimport java.util.regex.Pattern;
import java.util.regex.Matcher;
public class Utils {
public static void main
(String[] args
) { String[] tests
= new String[]{"ab",
"ab1",
"ab1-",
"2a-b",
"321321-asdfasdf-a-46546",
">?<",
null}; System.
out.
println(test
+ " " + is_valid
(test
)); }
}
public static boolean is_valid
(String code
) {
if(code == null) return false;
Pattern p;
Matcher m;
if(!code.contains("-")) return false;
p = Pattern.compile("\\d");
m = p.matcher(code);
if(!m.find()) return false;
p = Pattern.compile("\\w(.*)\\w");
m = p.matcher(code);
if(!m.find()) return false;
return true;
}
}