Ahmad Ahmad - 1 month ago 7
C# Question

using do while statement in method returning string

I am writing a program for shopping system. In this I am using array to get input from the brand name from the user. I am using method which returns string to get the input. Following is code:

public class Brand{
private string brandName;

public string BrandName
{
get { return brandName; }
set { brandName = value; }
}
public string getBrandName()
{
string[] brands = new string[5];
brands[0] = "Honda";
brands[1] = "Suzuki";
brands[2] = "Ferrari";
brands[3] = "BMW";
brands[4] = "Toyota";
Console.WriteLine("Please enter the brand name from the above given brands..");
string temp = Console.ReadLine();
do
{
try
{
for (int i = 0; i < 6; i++)
{
if (brands[i].Contains(temp))
{
this.BrandName = temp;
break;

}

}
return this.BrandName;
}
catch
{
Console.WriteLine("Your provide brand does not match with the database in our system. Please try another one.");
}
} while (BrandName!=temp);



}

}


The problem is that I am at beginner level and not getting the trick what should be in this while statement that it loops and asks user to input again and again until he enters the correct brand name. Please help me.

Answer

Maybe this will work based on your code:

public string getBrandName()
{
    string[] brands = new string[5];
    brands[0] = "Honda";
    brands[1] = "Suzuki";
    brands[2] = "Ferrari";
    brands[3] = "BMW";
    brands[4] = "Toyota";
    Console.WriteLine("Please enter the brand name from the above given   brands..");
    string temp = Console.ReadLine();
    while(!brand.Contains(temp))
    {
        Console.WriteLine("Your provide brand does not match with the database in our system. Please try another one.");
        temp = Console.ReadLine();
    }
    return temp;
}

Few things to notice:

  1. We will ask the user for a brand name.

  2. We will check that the input is a brand from brands list (you use contains to check if the input is in the char array of every brand name, watch the difference).

  3. If then name is in the list we will not enter inside the loop and we will return the brand name.

  4. If the name is not in the list we will ask the user again to insert a valid brand name until he will enter any and then we will return it.

Comments