Yuita A. Sari

“If you want to be a writer, you must do two things : read a lot and write a lot. There's no way around these two things that I'm aware of, no shortcut.” ― Stephen King

Random Alphabet Automatically

Leave a comment

This is one of ways that can face your problem of random String. Just random the index and you don’t need to type alphabet manually from A-Z, just use ASCII function and looping it. Here example of code [ using Java]

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package freeExercise;

import java.util.ArrayList;
import java.util.Random;

/**
 *
 * @author Yuita Arum Sari
 */
public class RandomAlphabet {

    static Random random = new Random();

    /**
     * Untuk merandom sebanyak inputan random, jika yang diinputkan panjang=5,
     * maka akan diisi sebanyak 5 elemen yang dirandom
     * @param panjang
     * @return
     */
    public static int[] getRandom(int panjang) {
        int[] rand = new int[panjang];
        for (int i = 0; i < rand.length; i++) {
            int hasil = random.nextInt(panjang);
            rand[i] = hasil;
        }
        return rand;
    }

    /**
     * Untuk mendapatkan increment alphabet secara otomatis
     * @return
     */
    public static ArrayList<String> getAlphabet(){
        ArrayList<String> listHuruf=new ArrayList<String>();
        for (int i = 65; i < 91; i++) {// menggunakan char ascii
            String huruf=Character.toString((char)i);
            listHuruf.add(huruf);
        }
        return listHuruf;
    }

    public static void main(String[] args) {
        System.out.println("**** Automatically Increment of Alphabet*****");
        ArrayList<String> list=getAlphabet();
        for (int i = 0; i < list.size(); i++) {
            System.out.println(list.get(i));
        }
        System.out.println("****Random sebanyak 5 huruf****");
        int[] angka = getRandom(5);
        for (int i = 0; i < angka.length; i++) {
            System.out.println(list.get(angka[i]));
        }
    }
}

#Just try it…


		

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s