Onde esta o erro?

3 respostas
faicoxim
class Listapalavras
{
	public static void main (String args[])
	{
		String[] wordlistone = {"Oi","eu","ja","sei","java"};
		String[] wordlisttwo = {"Foi","dificil","mas","consegui"};
		String[] wordlistthree = {"Estudei","muito","é","10"};
		
		//saber a quantidade de palavras nas variaveis acima
		int tamanhoum = wordlistone.length;
		int tamanhodois = wordlisttwo.length;
		int tamanhotres = wordlistthree.length;
		
		int aleatorioum = (int)(Math.random() * tamanhoum);
		int aleatoriodois = (int) (Math.random() * tamanhodois);
		int aleatoriotres = (int) (Math.random() * tamanhotres);
		
		String phrase = wordlistone[tamanhoum] + " " + wordlisttwo[tamanhodois] + " " + wordlistthree[tamanhotres];
		System.out.println(phrase);
		
	}
}

Seguinte mensagem após compilado

java.lang.ArrayIndexOutOfBoundsException: 5
at Listapalavras.main(Listapalavras.java:18)
Exception in thread "main"
Process completed.

3 Respostas

Lavieri

o erro esta no seguinte… os indices de uma array iniciam em 0, e sendo assim terminam sempre em length - 1

portanto nas chamadas dos itens da array, vc so pode chamar itens entre 0 e length - 1

quando vc faz

wordlistone[tamanhoum] vc chama um IndexOutOfBounds portanto o ultimo item é wordlistone[tamanhoum-1]

Ana.Pandini

O ‘lenght’ do array de String irá retornar para você a quantidade de elementos que você colocou nesse array.
Porém, os índices desses elementos são contados a partir de zero, portanto, para acessar o último elemento de um array de cinco posições, você deve fazer:

String[] wordList = {"um", "dois", "três"};
String ultimoElemento = wordList[2];
System.out.println(ultimoElemento);

A saída desse trecho será “três”.

furutani
Olá Veja abaixo o código corrigido
public static void main (String args[])
	{
		String[] wordlistone = {"Oi","eu","ja","sei","java"};
		String[] wordlisttwo = {"Foi","dificil","mas","consegui"};
		String[] wordlistthree = {"Estudei","muito","é","10"};
		
		//saber a quantidade de palavras nas variaveis acima
		int tamanhoum = wordlistone.length;
		int tamanhodois = wordlisttwo.length;
		int tamanhotres = wordlistthree.length;
		
		int aleatorioum =   1 + (int)(Math.random() * tamanhoum);
		int aleatoriodois = 1 + (int)(Math.random() * tamanhodois);
		int aleatoriotres = 1 + (int)(Math.random() * tamanhotres);
		
		String phrase = wordlistone[aleatorioum - 1] + " " + wordlisttwo[aleatoriodois - 1] + " " + wordlistthree[aleatoriotres - 1];
		System.out.println(phrase);
		
	}
Criado 28 de janeiro de 2009
Ultima resposta 28 de jan. de 2009
Respostas 3
Participantes 4