Well, I have a problem and I do not understand why it does not compare well the value of the string. I would appreciate all the help possible. By not sharing well the "numbers" (passed as string). the final string is larger than a long and gives an error.
EDIT: What it does is go putting Integers stored togetherNumeros in two strings, I do not look for them to add up, but they are equally distributed, that is: If altogether I have 9.9.6,5, 5,3,2,1. The strings should look like this:
s1 = 9 5 5 1
s2 = 9 6 3 2
It is not a sum of the numbers themselves, but it is dividing between the two strings
I do not know if I explained myself well, the compareTo
should give me 1
if this were so: "23".compareTo("15")
, no?
Here is the code fragment that gives me error:
long[] solucion = new long[2];
int c; //candidato
String cs;
while (!(conjuntoNumeros.isEmpty())){
//seleccionar candidato
c = seleccionarCandidato(conjuntoNumeros);
//eliminar candidato
conjuntoNumeros.remove(new Integer(c));
cs = String.valueOf(c);
if (s1.compareTo(s2)>=1){
s2 = s2 + cs;
}else{
s1 = s1 + cs;
}
}
System.out.println(s1 + " y " + s2);
solucion[0]=new Long(s1).longValue();
solucion[1]=new Long(s2).longValue();
return solucion;
cs is the string of the int that came out in the select candidate function
setNumeros is an arrayList containing integers
The idea of the code is to distribute equally and finish the two numbers or the same or that are very close to each other.
Here the candidate selection code:
This function searches for the largest number stored in the Arraylist of setNumeros.
int seleccionarCandidato(ArrayList<Integer> conjunto){
int candidato = conjunto.get(0);
for (int i=1; i<conjunto.size(); i++){
if(candidato < conjunto.get(i)) candidato = conjunto.get(i);
}
return candidato;
}
And finally the error code:
I get an error because I think the size of the string is much higher and should always be smaller (if it is distributed well).
Error code:
Exception in thread "main" java.lang.NumberFormatException: For input string: "9998777666655555554433322111"
at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
at java.lang.Long.parseLong(Long.java:592)
at java.lang.Long.<init>(Long.java:965)
at NumeroMasCercanos.VorazNumerosCercanos(NumeroMasCercanos.java:55)
at Pruebas.main(Pruebas.java:12)