随机字符串小写

时间:2013-04-03 23:56:37

标签: java substring uppercase lowercase

我需要创建一个由三个随机大写字母和三个随机数字组成的字符串,然后输出结果,我已经完成了。 接下来我需要使整个字符串小写,输出结果,然后只使第一个字符大写并输出结果。我一直在尝试使用substring(),但它没有编译,我不太确定如何将substring()与随机生成器一起使用。以下是我所写的内容,如果能得到一些帮助,那将会很棒。

import java.util.Random;

public class RandomString
{
    public static void main(String[] args)
    {  Random generator = new Random();

       int randomNumber = generator.nextInt(2);
       char randomChar = (char)('A');
       System.out.print("A random string is " + randomChar);

       randomNumber = generator.nextInt(26);
       randomChar = (char)('A' + randomNumber);
       System.out.print(randomChar);

       randomNumber = generator.nextInt(26);
       randomChar = (char)('A' + randomNumber);
       System.out.print(randomChar);

       randomNumber = generator.nextInt(10);
       System.out.print(randomNumber);

       randomNumber = generator.nextInt(10);
       System.out.print(randomNumber);

       randomNumber = generator.nextInt(10);
       System.out.println(randomNumber);

    }
}

3 个答案:

答案 0 :(得分:1)

// Get the string representation of the number
String sRandomNumber = Integer.toString(randomNumber);

// Convert to lower case
sRandomNumber = sRandomNumber.toLowerCase();

// Print it
System.out.println("In Lower Case: " + sRandomNumber);

// Make first char upper case
sRandomNumber = sRandomNumber.substring(0,1).toUpperCase() + sRandomNumber.substring(1);

// Print it again
System.out.println("With 1st char upper case: " + sRandomNumber);

答案 1 :(得分:0)

字符串是crate的方式是无关紧要的。给定任何字符串,将第一个字母大写,并将其余字母小写:

str = str.substring(0, 1).toUpperCase() + str.substring(1).toLowerCase();

答案 2 :(得分:0)

    // create a string of 3 random capital letters
    StringBuilder sb = new StringBuilder();
    Random random = new Random();
    for(int i = 0; i < 3; i++) {
        sb.append((char)('A' + random.nextInt(26)));
    }
    // and 3 random digits
    for(int i = 0; i < 3; i++) {
        sb.append(random.nextInt(10));
    }
    // output the result
    System.out.println(sb);
    // make this whole string lower case and output the result
    String lowerCase = sb.toString().toLowerCase();
    System.out.println(lowerCase);
    // make only the first character upper case and output the result
    System.out.println(lowerCase.substring(0, 1).toUpperCase() + lowerCase.substring(1));