Ordenacao de Vetores retornando estouro de array

3 respostas
diegohsi
Pessoal, eu sei que tem muitos for ai que dava pra diminuir mais ... nao sei o porque retornar a [color=red]Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 9 at ordenacao.Ordena2Vetores.main(Ordena2Vetores.java:39) [/color]
public class Ordena2Vetores {
	public static void main(String[] args) {
		
		int[] vetor1 = new int[5];
		int[] vetor2 = new int[5];
		int[] vetor3 = new int[vetor1.length + vetor2.length];
		int maior;
		
		System.out.println("Leitura do Vetor1: ");
		for(int i = 0; i < vetor1.length - 1; i++) {
			vetor1[i] = EasyIn.getInt();
		}
		
		System.out.println("Leitura do Vetor2: ");
		for(int j = 0; j < vetor1.length - 1; j++) {
			vetor1[j] = EasyIn.getInt();
		}
		
		for(int m = 1; m < vetor1.length; m++) {
			for(int n = vetor1.length-1; n >= m; n--) {
				if(vetor1[n-1] > vetor1[n]) { // Ordenando vetor1
					maior = vetor1[n-1];
					vetor1[n-1] = vetor1[n];
					vetor1[n] = maior;
				}
				//ordenando vetor 2
				if(vetor2[n-1] > vetor2[n]) {
					maior = vetor2[n-1];
					vetor2[n-1] = vetor2[n];
					vetor2[n] = maior;
				}
			}
		}
		
		for(int i = 1; i < vetor3.length; i++) {
			for(int j = vetor3.length-1; j >= i; j--) {
				if(vetor2[j] > vetor1[j]) {
					vetor3[j] = vetor2[j];
					vetor3[j-1] = vetor1[j];
				} else {
					vetor3[j] = vetor1[j];
					vetor3[j-1] = vetor2[j];
				}
			}
		}
		
		for(int k = 0; k <= vetor3.length; k++) {
			System.out.println(vetor3[k] + " ");
		}
	}
}

3 Respostas

tinorberto

Olá, vc esta acessando uma posição inválida de array, no caso a posição 9 do array vetor 1

Mais informações sobre a exception http://download.oracle.com/javase/6/docs/api/java/lang/ArrayIndexOutOfBoundsException.html

//note que vc percorre o vetor 3 de 0 a 9 ,depois vc usa isso para o vetor 2, com isso lança a exception 
for(int i = 1; i < vetor3.length; i++) {    
			for(int j = vetor3.length-1; j >= i; j--) {
				if(vetor2[j] > vetor1[j]) {
					vetor3[j] = vetor2[j];
					vetor3[j-1] = vetor1[j];
				} else {
					vetor3[j] = vetor1[j];
					vetor3[j-1] = vetor2[j];
				}
			}
diegohsi

tinorberto desculpa mais nao entendi

diegohsi

Entendi Tionoberto valeu

Criado 2 de outubro de 2010
Ultima resposta 2 de out. de 2010
Respostas 3
Participantes 2