Java Random Number getNumber()

Here you can find the source of getNumber()

Description

Gets number.

License

Apache License

Return

{String} 4 random number

Declaration

public static String getNumber() 

Method Source Code

//package com.java2s;
/*//from  w  w w  .  java  2 s  .  c  o m
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License.  You may obtain a copy of the License at
 * 
 *      http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

import java.util.Random;

public class Main {
    /**
     * Gets number.
     *
     * @return {String} 4 random number
     */
    public static String getNumber() {

        Random r = new Random();
        StringBuffer sb = new StringBuffer();

        for (int i = 0; i < 4; i++) {
            sb.append(getRandomChar(r.nextInt(1)));
        }

        return String.valueOf(sb);
    }

    /**
     * Gets random char.
     *
     * @param x 0: 0~9; 1: A~Z; 2: a~z; other: word
     * @return {char}
     */
    public static char getRandomChar(int x) {

        Random r = new Random();
        char c = '0';

        // 48-57 65-90 97-122 u4e00~9fa5 u9fff
        switch (x) {
        case 0:
            c = (char) (r.nextInt(10) + 48); //0 ~ 9
            break;
        case 1:
            c = (char) (r.nextInt(26) + 97); //A ~ Z
            break;
        case 2:
            c = (char) (r.nextInt(26) + 65); //a ~ z
            break;
        default:
            String s = Integer
                    .toHexString((r.nextInt(0x9fa5 - 0x4e00) + 0x4e00));
            c = (char) Integer.parseInt(s, 16);
            break;
        }

        return c;
    }
}

Related

  1. getFlightNumber()
  2. getNextRandomNumber()
  3. getNum(int length)
  4. getNumAndWord(int length)
  5. getNumber()
  6. getNumber(int _nX0, int _nX1)
  7. getNumber(int length)
  8. getNumber(int length)
  9. getNumber(int length)