ALx ALx ALx ALx - 1 year ago 121
Java Question

Java check String and match

I am trying to do a math operation and match a letter of a string:

I got this table:

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


And I am getting inputs from keyboard of ID's that are in 012345678X (8 digits + 1 char)

I am trying to make it check for 8digits+1char and got it done like this:

public void check() {
status = true;}

My problem is that now I need to check the last entered letter matches the table by calculating the numbers of the input % 23.
Example of valid inputs:

  • 00000102X since 102 % 23 = 10 and X is 10th letter in my char list;

  • 24659213Q since 24659213 % 23 = 16 and Q is 16th letter in char list.

Now what I did try is this:

int num = Integer.parseInt(input.replaceAll("[^0-9]", ""));
case 0: if(num%23==0){
status = true;
case 10: if(num%23==10){
status = true;

default: status = false;

But with no results, any idea where am I going wrong? It's not that I get a compilation or code error, just that every 8digit+1letter input I get it gets accepted. Thank you in advance!


import java.util.Scanner;
public class Testing {

static final char[] LETRAS = {'T', 'R', 'W', 'A', 'G', 'M', 'Y', 'F', 'P', 'D', 'X'
,'B', 'N', 'J', 'Z', 'S', 'Q', 'V', 'H', 'L', 'C'
, 'K', 'E'};
String input;
public boolean status = false;
Scanner scanner = new Scanner(;

//Método problema general
public static void main (String[] args) {
Testing programa = new Testing();

public void inicio() {
while (!status){

//Explicar programa
public void Intro() {
System.out.println("¡Hola!\nEste programa pide y comprueba DNI's."
+ "A continuación va a pedir un DNI de forma 8 dígitos y una letra,"
+ "y va a comprobar si es válido.\n"
+ "Ejemplo DNI válido: 24659213Q\n\n");

//Métodos primer nivel de decomposición
//Pedir DNI por teclado
public void datosUsuario() {
System.out.print("Escribe DNI: ");
input = scanner.nextLine();

//Comprobación DNI
public boolean comprobacion() {
System.out.println("Comprobamos DNI...");
char letra = input.charAt(8);
int numeros = Integer.parseInt(input.replaceAll("[^0-9]", ""));
if(LETRAS[numeros%LETRAS.length] == input.charAt(8)) {
return true;
return false;

//Mostrar resultado
public void resultado() {
System.out.println("DNI válido!");

Answer Source

I see many problems in your code , first I am not sure why is the switch for? you can simply do it like this

    public static boolean isValid(String str) {

    if(str.matches("[0-9]{8}[TRWAGMYFPDXBNJZSQVHLCKE]{1}")) {
        int num = Integer.parseInt(str.replaceAll("[^0-9]", ""));
        if(LETTERS[num%LETTERS.length] == str.charAt(8) ) {
            return true;
    return false;
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download