Verify if there are whole numbers in a chain?

1

I have made this code:

 public static void main (String []args){
    Lexico lex = new Lexico();
    String cadena = JOptionPane.showInputDialog("Ingrese la cadena: ");
    System.out.println(lex.ingresarCadena(cadena));

 }   

    String[] Ecuacion1;
public  String ingresarCadena(String cadena)
    {
     String c ="";
     Ecuacion1 = cadena.split("(\+|\-|\*|\=|\%|\/)");
     for(int i = 0; i < Ecuacion1.length; i++)
    {
        System.out.print(Ecuacion1[i]);
    }
    return c;
 }

but I want to make a method that tells me if there are whole numbers in that vector.

    
asked by Chavarría Agudelo 24.10.2018 в 16:51
source

1 answer

0

Your idea is correct, you can do it using a loop to check each character in the chain,

   private static boolean checkNumericValues(String cadena){        

      String[] caracteres =  cadena.split("");
      for(int i = 0; i < caracteres.length; i++)
        {
           try{             
                Integer.parseInt(caracteres[i]);             
                return true; //Existe al menos un caracter numerico.
           }catch (NumberFormatException e){ 
               System.out.println(" is not a valid integer number : " + e.getMessage()); 
           }                         
        }     

        return false; //No existen caracteres numericos

   }

but I think the best option would be using a REGEX to detect numerical values:

String regex = ".*\d+.*";

creates a method to verify if the string contains numeric values, if there is at least one numeric value the method will return true , otherwise false :

private static boolean checkNumericValues(String cadena){        

  String regex = ".*\d+.*"; 
  Pattern pattern = Pattern.compile(regex);      

  return  pattern.matcher(cadena).matches();

}
    
answered by 24.10.2018 / 18:39
source