Random Alphabet Automatically

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]

[code language=”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]));
}
}
}
[/code]

#Just try it…



			

Leave a Reply

Your email address will not be published. Required fields are marked *