How can I compare a String with an Int?

0

The problem is that I'm doing a project where requests for bank accounts are made either people or companies, but I need to sort the requests in lists, I made the People as they ask me to order them by their ID number, but companies have to order them by their code and organization, then the code is a int and the organization a String , how can I make that comparison?

    
asked by Arnaldo Robaina 01.06.2017 в 21:22
source

3 answers

2

If you want to compare the organization code (int) with the name (String) it would be something as simple as:

int codigo_empresa = 5; 
String nombre_empresa = "5";
int comparacion = codigo_empresa == Integer.parseInt(nombre_empresa)? 0 : codigo_empresa < Integer.parseInt(nombre_empresa)? -1 : 1;

Being that if the comparison is 0 are equal, if it is -1 the code is smaller and if it is 1 is greater.

But I sincerely doubt that this is what you want, if you want to order by your code and then within that order by name something like

  

cod nombre

     

01 a

     

01 b

     

02 a

     

02 c

Well in that case first order them by code and separate them into different lists and then alphabetize them, to sort alphabetically you use the function.

Collections.sort(nombre_array_strings);

I hope it helps you.

    
answered by 01.06.2017 в 21:54
0
  

To move from String to Integer, there are several options.   I usually choose to use the Integer.parseInt (String string) method

Example:

String numStr = "35";
int numInt = Integer.parseInt(numStr);
  

Possible problems that we can find:

That the chain contains spaces (both at the ends and between the characters). We solve this by using the trim() method to eliminate spaces from the extremes, and we can use the String.replaceAll() method for spaces between characters.

Example:

String numStr = "   3  5   ";
// Eliminamos los espacios de los extremos:
numStr.trim();
// Eliminamos los espacios del interior de la cadena
numStr.replaceAll(" ", "");
// Aquí ya podríamos parsear a Integer sin problema aparente

I hope it helps you

    
answered by 01.06.2017 в 21:51
0

You can convert the variable String to int and that you can do it like this:

String numero1="2345";
int numero2=4567;
int temp1=Integer.valueOf(numero1); // aqui convertimos el String a int
if(temp1<numero2){
   System.out.println("Entonces el numero 2 es mayor");
}
    
answered by 01.06.2017 в 21:33