dúvida de implementação

5 respostas
E

Sou iniciante em Java e estou estudando pelo livro do deitel, java como programar, 6ª edição.
estou com dúvida num exercício, que é esse:

minhas classes são essas:

public class IntegerSet {

	//variáveis de instância
	//private int elemento[] = new int[101];
	private boolean set[] = new boolean[101];
	
	//contrutor
	public IntegerSet(int a[]) {
		for (int i = 0; i < set.length; i++) {
			for (int j = 0; j < a.length; j++) {
				if (a[j] == i)
					set[i] = true;
			}
		}	
	}
	
	//métodos
//	public void montaSet(int x[]) {
//		for (int id : x)
//			set[id] = true;
//	}
	
	public void union(boolean set1[], boolean set2[]) {
		//boolean setUnion[] = new boolean[101];
		String strUnion = "";
		for (int i = 0; i < set1.length; i++) {
			if (set1[i] || set2[i]) 
				strUnion = strUnion + i + " ";
		}
		System.out.printf("\n\nResultado da união:\n%s", strUnion);
	}
	
	public void intersection(boolean set1[], boolean set2[]) {
		//boolean setIntersection[] = new boolean[101];
		String strIntersection = "";
		for (int i = 0; i < set1.length; i++) {
			if (set1[i] && set2[i]) 
				strIntersection = strIntersection + i + " ";
		}
		System.out.printf("\n\nResultado da intersecção:\n%s", strIntersection);
	}
	
	public void insertElement(int i, boolean set1[]) {
		set1[i] = true;
	}
	
	public void deleteElement(int i, boolean set1[]) {
		set1[i] = false;
	}
	
	public String toSetString(int set1[]) {
		String str = "";
		int colunas = 0;
		for (int i = 0; i < set.length; i++) {
			if (set1[i] == i) {
				str = str + i + " ";
			}
			else {
				str = str + "-- ";
			}
			colunas++;
			if (colunas % 10 == 0)
				str = str + "\n";
		}
		return str;
	}
	
	public boolean isEqualTo(boolean set1[], boolean set2[]) {
		boolean saoIguais = true;
		while (saoIguais) {
			for (int i = 0; i < set1.length; i++) {
				if (set1[i] != set2[i]) 
					saoIguais = false;
			}
		}
		return saoIguais;
	}
}
public class IntegerSetTeste {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub

		int array1[] = {0, 10, 20, 30, 40, 50, 60, 70, 80, 90, 100};
		int array2[] = {0, 10, 20, 30, 35, 45, 55, 65, 75, 80, 90, 100};
		
		IntegerSet s1 = new IntegerSet(array1);
		IntegerSet s2 = new IntegerSet(array2);
		
//		set_1.montaSet(array1);
//		set_2.montaSet(array2);
		
		System.out.println("Set 1: \n" + s1.toSetString(array1));
		System.out.println("Set 2: \n" + s2.toSetString(array2));
		
		//set_1.isEqualTo();
		
		
	}

}

minhas dúvidas são essas:
ele pede para criar objetos boolean, e um construtor sem parametros que cria todos os elementos como false, mas não estou sabendo como fazer esse construtor sem parametros e como criar os objetos…
se alguém tiver a fim de estudar esse problema, valeu…

5 Respostas

_
public class IntegerSet {
    public IntegerSet() {
        for( int i = 0; i < set.length; i++ )
            set[ i ] = false;
    }
}

Mas isto não deveria ser necessário, dado que arrays de boolean são inicializados como false.

T
import java.util.Arrays;

/*
 Cada objeto IntegerSet pode 
 armazenar inteiros no intervalo de 0 a 100. O conjunto é 
 representado por um array de booleans. O elemento do 
 array a[i] é true se o inteiro i estiver no conjunto. O 
 elemento do array a[j] é false se o inteiro j não 
 estiver no conjunto.   
 */

/**
 * @author 
 *
 */
public class IntegerSet {

    private static final int MIN = 0;

    private static final int MAX = 100;

    private boolean[] a; // [0...100]

    /**
     O construtor sem argumento 
     inicializa o array java como conjunto vazio (isto é, um 
     conjunto cuja representação de array contém todos os 
     valores false).
     */
    public IntegerSet() {
        a = new boolean[MAX + 1];
    }

    /**
     O método 
     union, que cria um terceiro conjunto com a união teórica 
     de dois conjuntos existentes
     * @param c1
     * @param c2
     * @return
     */
    public static IntegerSet union(IntegerSet c1, IntegerSet c2) {
        IntegerSet r = new IntegerSet();
        for (int i = 0; i <= MAX; ++i) {
            r.a[i] = c1.a[i] | c2.a[i];
        }
        return r;
    }

    /**
     o método intersection, que 
     cria um terceiro conjunto com a intersecção teórica de 
     dois conjuntos existentes;   
     * @param c1
     * @param c2
     * @return
     */
    public static IntegerSet intersection(IntegerSet c1, IntegerSet c2) {
        IntegerSet r = new IntegerSet();
        for (int i = 0; i <= MAX; ++i) {
            r.a[i] = c1.a[i] & c2.a[i];
        }
        return r;
    }

    /**
     o método insertElement que 
     insere um novo elemento num conjunto;
     * @param i
     */
    public void insertElement(int i) {
        a[i] = true;
    }

    /**
     o método 
     deleteElement que exclui um elemento de um conjunto;
     * @param i
     */
    public void deleteElement(int i) {
        a[i] = false;
    }

    /**
     e o método toSetString que retorna uma string 
     contendo os elementos do conjunto, ou um - caso a 
     posição daquele elemento seja false.
     * @return
     */
    public String toSetString() {
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i <= MAX; ++i) {
            if (a[i])
                sb.append(i).append(",");
            else
                sb.append("-").append(",");
        }
        return sb.toString();
    }

    /**
     o 
     método isEqualTo que determina se dois conjuntos são 
     iguais,   
     * @param c1
     * @param c2
     * @return
     */
    public static boolean isEqualTo(IntegerSet c1, IntegerSet c2) {
        return Arrays.equals(c1.a, c2.a);
    }
}
E

obrigado pelas respostas!

thingol: valeu pelo código bem completo, me deu várias idéias. mas eu estou me perdendo numa parte bem básica: não sei como instanciar um objeto IntegerSet no método main (criei uma classe UseIntegerSet). não sei se esse problema tem algo diferente dos outros que eu fiz até agora, mas instanciei um objeto set1 com o comando abaixo:

IntegerSet set1 = new IntegerSet();

mas depois disso, não to conseguindo associar um array de inteiros nesse objeto, nem de booleans, que não deve ser o caso, ele tem que ser de inteiros…
valeu de novo.

T

O seu exercício não menciona que você pode ter um construtor que recebe um array de inteiros. Se você for usar a minha classe, então você teria algo como:

IntegerSet s1 = new IntegerSet ();
                IntegerSet s2 = new IntegerSet ();
 		int array1[] = {0, 10, 20, 30, 40, 50, 60, 70, 80, 90, 100};
 		int array2[] = {0, 10, 20, 30, 35, 45, 55, 65, 75, 80, 90, 100};
                for (int x : array1) {
                    s1.insertElement (x);
                }
                System.out.println (s1.toSetString());
                for (int x : array2) {
                    s2.insertElement (x);
                }
                System.out.println (s2.toSetString());
                IntegerSet uniao = IntegerSet.union (s1, s2);
                System.out.println (uniao.toSetString());
                IntegerSet interseccao = IntegerSet.intersection (s1, s2);
                System.out.println (interseccao.toSetString());
                System.out.println (IntegerSet.isEqualTo (s1, s2));
E

bah, cara… valeu mesmo.
eu estava tentando instanciar um objeto já com o array completo e nem me dei conta do insertElement…

mas sem querer te alugar demais, não entendi outra coisa:
eu não conhecia o formato de instanciação que você usou abaixo:

IntegerSet interseccao = IntegerSet.intersection (set1, set2);

e fui testar na forma que eu conhecia:

IntegerSet uniao = new IntegerSet();
        uniao.union (set1, set2);
        System.out.println ("União: \t\t" + uniao.toSetString());

mas desse jeito a união fica vazia. Por que?

Muito obrigado de novo e abraço.

Criado 17 de maio de 2006
Ultima resposta 18 de mai. de 2006
Respostas 5
Participantes 3