Wusion
Wusion

Reputation: 25

How to print a portion of the String, using Random class, in Java?

My goal is to print a portion (5 characters) from the string, using the Random class.

I have already figured out how to randomly print one character from the string, but my goal is to print 5 characters. My code so far:

import java.util.Random;

public class Training {
    public static void main(String[] args) {
        String text = "abcdefghijklmnopqrstuvwxyz";
        Random random = new Random();

        int i = 5;

        System.out.println(text.charAt(random.nextInt(text.length())));
        System.out.println(text.charAt(random.nextInt(text.length())));
        System.out.println(text.charAt(random.nextInt(text.length())));
    }
}

The expected output must be any 5 consecutive characters from the String. For exapmle:

hijkl
cdefg
abcde

Upvotes: 0

Views: 335

Answers (4)

Oleg Cherednik
Oleg Cherednik

Reputation: 18245

final String text = "abcdefghijklmnopqrstuvwxyz";
final Random random = new Random();
final int length = 5;

for (int i = 0; i < 3; i++) {
    int pos = random.nextInt(text.length() - length)
    System.out.println(text.substring(pos, pos + length));
}

As alternative to create substring, you can print separate characters:

for (int i = 0; i < 3; i++) {
    for (int j = 0, pos = random.nextInt(text.length() - length); j < length; j++)
        System.out.print(text.charAt(pos + j));
    System.out.println();
}

Upvotes: 1

VienNguyen
VienNguyen

Reputation: 12

I think you can use the API substring(int startIndex, int endIndex). You need to pass startIndex as a random number (endIndex = startIndex + 5). For more detail, you can refer substring.

Note:

Don't forget to check the value of startIndex. It can over your string length and throw an exception.

Upvotes: 0

yuvgin
yuvgin

Reputation: 1362

Generate a random integer and use it to print a substring of the string:

String text = "abcdefghijklmnopqrstuvwxyz";
Random random = new Random();

int i = 5;  // define the length of the substring

int index = random.nextInt(text.length() - i);  // get a random starting index


System.out.println(text.substring(index, index + i)); // print the substring

Upvotes: 0

hrytsea32
hrytsea32

Reputation: 1

You need an additional variable to store the random value, i.e

String text = "abcdefghijklmnopqrstuvwxyz";
Random random = new Random();

int i = 5, r;

for(int j = 0; j < 3; j++) {
    r = random.nextInt(text.length() - i)
    System.out.println(text.substring(r, r + i));
}

Upvotes: 0

Related Questions