[quote=novato25]Então tenta isso:
[code]public class Main2 {
public static void main(String[] args) {
int[] vetor = {1, 2, 3, 4, 5, 6, 7, 8, 11, 15, 22, 23, 24, 25, 26, 27, 28, 35, 39 };
//int[] vetor = {1, 2, 5, 6, 7, 8, 10, 11, 20, 30, 40 };
int cont = 0;
StringBuilder str = new StringBuilder();
String c = String.valueOf(vetor[0]);
for(int i=0; i<vetor.length; i++) {
if(i < vetor.length -1) {
if(vetor[i] + 1 == vetor[i + 1]) {
cont++;
continue;
}
}
if(cont == 1) {
str.append(c).append(",").append(vetor[i]);
cont=0;
} else if(cont > 1) {
str.append(c).append(" a ").append(vetor[i]);
cont=0;
} else {
str.append(vetor[i]);
}
if(i < vetor.length-1) {
str.append(",");
c = String.valueOf(vetor[i + 1]);
}
}
System.out.println(str);
}
}[/code]
[/quote]
Muito bom o seu código.
Fiz algumas pequenas alterações e em princípio está funcionando como o esperado.
[code] public String sequencia(List numeros) {
int cont = 0;
StringBuilder str = new StringBuilder();
String c = String.valueOf(numeros.get(0));
for(int i=0; i<numeros.size(); i++) {
if(i < numeros.size() -1) {
if(numeros.get(i) + 1 == numeros.get(i + 1)) {
cont++;
continue;
}
}
if(cont == 1) {
str.append(c).append(", ").append(numeros.get(i));
cont=0;
} else if(cont > 1) {
str.append(c).append(" a ").append(numeros.get(i));
cont=0;
} else {
str.append(numeros.get(i));
}
if(i < numeros.size()-1) {
str.append(", ");
c = String.valueOf(numeros.get(i + 1));
}
}
return str.toString();
}
[/code]
Vou aprofundar os testes.
Valeu!!!