user2242717
user2242717

Reputation: 1

Making a random string lower case

I need to create a string of three random capital letters and three random digits, and output the result, which I have done. Next I need to make this whole string lower case, output the result, then make only the first character upper case and output the result. I've been trying to use substring(), but it isn't compiling and I'm not too sure how to use substring() with random generator. Here is what I have written and it would be great if i could get some help.

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);

    }
}

Upvotes: 0

Views: 3737

Answers (3)

Evgeniy Dorofeev
Evgeniy Dorofeev

Reputation: 136062

    // 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));

Upvotes: 0

Vaibhav Desai
Vaibhav Desai

Reputation: 2728

// 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);

Upvotes: 1

Bohemian
Bohemian

Reputation: 425208

The way the string is crates is irrevant. Given any string, to capitalise the first letter, and lowercase the rest:

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

Upvotes: 0

Related Questions