thingol 5 de mai. de 2009
Dica: new int[3] cria um array com os elementos indexados [0], [1] e [2].
Seu código está tentando acessar o elemento de índice [3] (veja os “fors”). Como [3] não existe vai gerar a tal exceção.
tinorberto 5 de mai. de 2009
Esse tipo de exceção Exception in thread “main” java.lang.ArrayIndexOutOfBoundsException: 3 e gerada quando tentamos acessar uma posição que não existe em um vetor , de uma olhada em seu codigo vc essta usando j<=total dentro de um for , logo num[j]; pode assumir num[total] então vai lançar o erro.
alanmartins 5 de mai. de 2009
Valeu Pessoal, fiz o seguinte teste agora.
public class ordem {
public static void main ( String [] args ) {
int i = 0 ;
int j = 0 ;
int aux ;
int [] num = new int [ 9 ] ;
int total = num . length ;
num [ 0 ] = 10 ;
num [ 1 ] = 8 ;
num [ 2 ] = 6 ;
num [ 3 ] = 4 ;
num [ 4 ] = 65 ;
num [ 5 ] = 34 ;
num [ 6 ] = 1 ;
num [ 7 ] = 230 ;
num [ 8 ] = 150 ;
for ( i = 0 ; i <= 9 - 1 ; i ++ ){
for ( j = i + 1 ; j <= 8 ; j ++ ){
if ( num [ i ]> num [ j ] ){
aux = num [ i ] ;
num [ i ] = num [ j ] ;
num [ j ] = aux ;
}
}
}
for ( i = 0 ; i <= total ; i ++ ){
System . out . println ( num [ i ] );
}
}
}
Ele dá o mesmo erro, mas mostra o resultado certo.
1
4
6
8
10
34
65
150
230
Marky.Vasconcelos 5 de mai. de 2009
Por que voce continua indo até <= tira o ‘=’.
alanmartins 5 de mai. de 2009
É galera eu tirei o igual e vim aqui responder e vi que vocês disseram o mesmo.
Obrigado pela ajuda!
Segue o código correto, sempre alguém precisa desse tipo de lógica.
public class ordem {
public static void main ( String [] args ) {
int i = 0 ;
int j = 0 ;
int aux ;
int [] num = new int [ 9 ] ;
int total = num . length ;
num [ 0 ] = 10 ;
num [ 1 ] = 8 ;
num [ 2 ] = 6 ;
num [ 3 ] = 221 ;
num [ 4 ] = 65 ;
num [ 5 ] = 34 ;
num [ 6 ] = 300 ;
num [ 7 ] = 3 ;
num [ 8 ] = 50 ;
for ( i = 0 ; i < total ; i ++ ){
System . out . println ( "i " + i );
for ( j = i + 1 ; j < total ; j ++ ){
System . out . println ( "j " + j );
if ( num [ i ]> num [ j ] ){
aux = num [ i ] ;
num [ i ] = num [ j ] ;
num [ j ] = aux ;
}
}
}
for ( i = 0 ; i < total ; i ++ ){
System . out . println ( num [ i ] );
}
}
}
Valeu pessoal, até mais!
davisamaral 5 de mai. de 2009
Ou se Preferir…
public static void main ( String [] args ) {
int [] num = { 10 , 8 , 6 , 4 , 65 , 34 , 1 , 230 , 150 };
for ( int i = 0 ; i < num . length ; i ++ ) {
int j = i + 1 ;
while ( j < num . length ) {
if ( num [ i ] > num [ j ] ) {
int aux = num [ i ] ;
num [ i ] = num [ j ] ;
num [ j ] = aux ;
}
j ++ ;
}
}
for ( int i : num ) {
System . out . println ( i );
}
}
alanmartins 5 de mai. de 2009
Blz!
Valeu Cara, fico agora com mais uma carta na manga!
Valeu mesmo…