hi,

I have to do a program that generates 'n' different combinations of 7 different numbers between 1 and 49, so I did this:

``````import java.util.*;
public class Totoloto {

public static void main(String[] args) {
System.out.print("Quantas apostas?");
Scanner s = new Scanner(System.in);
int n=s.nextInt();
int[][] apostas = geraApostas(n);
for(int i=0;i<apostas.length;i++)
{
System.out.print("[");
for(int a=0;a<7;a++)
{
System.out.print(apostas[i][a]);
if(a!=6)
System.out.print(", ");
}
System.out.println("]");
}
}

private static int[] geraAposta(){
int[] aposta = new int[7];
for(int i=0;i<7;i++)
{
int num;
Boolean existe;
do{
existe=false;
num=(int) (Math.random()*49+1);
for(int a=0;a<7;a++)
if(aposta[a]==num)
existe=true;
}while(existe);
aposta[i]=num;
}
return aposta;
}

private static int[][] geraApostas(int n){
int[][] apostas = new int[7][n];
System.out.println(n + "" + apostas.length);
for(int i=0;i<n;i++)
{
int[] aposta;
Boolean existe;
do{
existe=false;
aposta=geraAposta();
for(int a=0;a<n;a++)
if(apostas[n]==aposta)
existe=true;
}while(existe);
apostas[i]=aposta;
}
return apostas;
}
}``````

When I run it:

``````Quantas apostas?9
97
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 9
at Totoloto.geraApostas(Totoloto.java:54)
at Totoloto.main(Totoloto.java:12)``````

This happens cecause, for int[][] apostas = new int[7][n];, apostas.lenght equals 7! how can I obtain 'n' with just the array and the length function?

thanks in advance!

You are very close there: `int[][] apostas = new int[n][7];` You want 'n' elements that each contain an array of 7 elements. Your outer loop `for(int i=0;i<n;i++)` then denotes that first dimension, so `aposta[i]=geraAposta();`

You are very close there: `int[][] apostas = new int[n][7];` You want 'n' elements that each contain an array of 7 elements. Your outer loop `for(int i=0;i<n;i++)` then denotes that first dimension, so `aposta[i]=geraAposta();`

thank you very much! problem solved.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.