In: Computer Science
Write a JAVAprogram that reads a word and prints all its substrings, sorted by length. It then generates a random index between 0 and the length of the entered word, and prints out the character at that index.
For example, if the user provides the input "rum", the program
prints
r
u
m
ru
um
rum
The random index generated is 1. The character at index 2 is u.
import java.util.Scanner;
import java.util.Random;
public class Main
{
public static void main(String[] args)
{
//variable declaration
String s;
int n, randNum;
Scanner sc = new
Scanner(System.in);
//display message
System.out.print("Enter a
string: ");
//input string
s = sc.nextLine();
//calculate the length of the
input string
n = s.length();
//generate random
number
Random rand = new
Random();
randNum = rand.nextInt(n);
//display message
System.out.println("The
substring are: ");
//generate all
substring
for (int len = 1; len <=
n; len++)
{
for (int i = 0; i <= n - len; i++)
{
int j = i + len - 1;
for (int k = i; k <= j; k++)
{
System.out.print(s.substring(k, k+1));
}
System.out.println();
}
}
//display character at random position
System.out.println("\nThe random number generated is " + randNum +
". The character at index " + randNum + " is " +
s.charAt(randNum-1));
}
}
OUTPUT:
