// Implementazione di un contatore binario. class SeqBit{ /* Se il problema fosse di scrivere sequenze di 4 bit potremmo procedere cosi`: for( int b3 = 0; b3 < 2; b3++ ) for( int b2 = 0; b2 < 2; b2++ ) for( int b1 = 0; b1 < 2; b1++ ) for( int b0 = 0; b0 < 2; b0++ ) System.out.println( "" + b3 + b2 + b1 + b0 ); Voglio pero` un'implementazione basata su metodi, che non risenta della limitazione dei 4 bit, ma possa anche costruire sequenze di 3 bit, di 6, di 8, di... */ public static String contatoreAzzerato( int nrBit ){ // Inizializzazione di un contatore costituito // di soli '0' e di pre-assegnata lunghezza. String ktr = ""; for( int i = 0; i < nrBit; i++ ) // ktr = ktr + '0'; ktr += '0'; return ktr; } public static boolean contatoreEstAzzerato( String ktr ){ // Verificatore dello stato di un contatore: restituisce true // se e solo il contatore ktr e` costituito di soli zeri. boolean ottimista = true; for( int i = 0; i < ktr.length(); i++ ) // ottimista = ottimista && ktr.charAt( i ) == '0'; ottimista &= ktr.charAt( i ) == '0'; return ottimista; } public static String contatoreAggiornato( String ktr ){ // Aggiorneremo da sinistra anziche` da destra, // come richiederebbero le consuetudini; a voi // il compito di rettificare questa scorrettezza. String agg = ""; // contatore aggiornato // Esempio: // Se ktr vale "0000" il risultato sara` "1000" // Se ktr vale "1000" il risultato sara` "0100" // ... // Se ktr vale "1100" il risultato sara` "0010" // ... // Se ktr vale "1111" il risultato sara` "0000" for( int i = 0; i < ktr.length() && ktr.charAt( i ) == '1' ; i++ ) agg += '0'; if ( agg.length() != ktr.length() ) // ktr non ancora spazzolato per intero { agg += '1'; for( int j = agg.length(); j < ktr.length(); j++ ) agg += ktr.charAt( j ); } return agg; } public static void main( String[] aa ){ // collaudo usa-e-getta int quantiBit = Leggi.leggiInt( ); String ktr = contatoreAzzerato( quantiBit ); int i = 0; do{ System.out.println( (++i)+": "+ ktr ); ktr = contatoreAggiornato( ktr ); } while( ! contatoreEstAzzerato( ktr ) ); } }