user3290428
user3290428

Reputation: 63

Homework Help w/ strings

  1. The follow given class prints random lower case strings. Each character in the string comes from the corresponding ASCII decimal code. In the Main, use this class to generate three (3) random strings, whose lengths are 8, 26, and 80, respectively.

    class RandomString 
    {
    
         public static void myString(int n)
         {
    
             Random rand = new Random ();
             for(int i = 1; i<=n; i++)
             {            
                 int x = rand.Next (97, 121);
                 char c = (char)x;
                 Console.Write(c);
             }
             Console.WriteLine();
    
         }
    
     }
    
  2. Modify the class in 2 so that it can print upper case strings. In the Main, generate some upper case strings, whose length is determine from the keyboard input. Hint: you need to find the ASCII code for upper case alphabetic first.

This is what I have so far:

class RandomString
{

    public static void myString(int n)
    {

        Random rand = new Random();
        for (int i = 1; i <= n; i++)
        {
            int x = rand.Next(97, 121);
            char c = (char)x;

            Console.Write(c);
        }
        Console.WriteLine();

    }
}
class Program
 {

        static void Main(string[] args)
        {
            //Question 2
            RandomString.myString(8);
            RandomString.myString(26);
            RandomString.myString(80);

            //Question 3
            Console.WriteLine("How big is your string?");
            int num = int.Parse(Console.ReadLine());
            RandomString.myString(num);


        }

  }

How do I complete question 3?

Upvotes: 1

Views: 107

Answers (1)

Mureinik
Mureinik

Reputation: 312259

The original code randomizes a number between 97 (which is the ascii code for a) and 122 (which is the ascii code for z). If you consult an ascii table, you'll see that the code for A is 65 and for Z is 90. So you could just replace the constants in the source and get:

public static void myString(int n)
{

    Random rand = new Random();
    for (int i = 1; i <= n; i++)
    {
        int x = rand.Next(65, 90); // Changed here.
        char c = (char)x;

        Console.Write(c);
    }
    Console.WriteLine();
}

From a software engineering perspective, though, you'd probably want to extract the common code:

public static void myString(int n, int lowerBound, int uppedBound)
{

    Random rand = new Random();
    for (int i = 1; i <= n; i++)
    {
        int x = rand.Next(lowerBound, upperBound); // Changed here.
        char c = (char)x;

        Console.Write(c);
    }
    Console.WriteLine();
}

public static void myLowerCaseString(int n)
{
    myString (97, 122);
}

public static void myUpperCaseString(int n)
{
    myString (65, 90);
}

Upvotes: 2

Related Questions