0

我需要创建一个由三个随机大写字母和三个随机数字组成的字符串,并输出我已经完成的结果。接下来我需要将整个字符串变为小写,输出结果,然后只将第一个字符变为大写并输出结果。我一直在尝试使用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);

    }
}
4

3 回答 3

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);
于 2013-04-04T00:02:42.790 回答
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));
于 2013-04-04T03:15:45.143 回答
0

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

str = str.substring(0, 1).toUpperCase() + str.substring(1).toLowerCase();
于 2013-04-04T00:05:07.153 回答