User input must be equal to one of 5 different strings, if not the user must input again, until the input is equal to one of the 5 strings.
I wrote some code, it works the way it should if the first entered input is equal to one of the 5 strings, if it is not, the program is stuck in an endless loop.
novaDrzava.PrevladujocaVera = Console.ReadLine();
var vera = novaDrzava.PrevladujocaVera;
var prvacrkaVera = vera.Substring(0, 1);
var ostaloVera = vera.Substring(1, vera.Length - 1);
prvacrkaVera = prvacrkaVera.ToUpper();
ostaloVera = ostaloVera.ToLower();
vera = prvacrkaVera + ostaloVera;
while (true)
{
if(vera == "Krščanstvo")
{
break;
}
if (vera == "Krscanstvo")
{
break;
}
if (vera == "Hinduizem")
{
break;
}
if (vera == "Islam")
{
break;
}
if (vera == "Budizem")
{
break;
}
Console.WriteLine("Vnesite ustrezno vero");
vera = Console.ReadLine();
vera = prvacrkaVera + ostaloVera;
}
I can't fully read your code since the identifiers aren't in English. But, given the rest of your question, I think this might be what you want:
var words = new List<string>
{
"Krščanstvo",
"Krscanstvo",
"Hinduizem",
"Islam",
"Budizem"
};
while (true)
{
var input = Console.ReadLine();
if (words.Contains(input, StringComparer.InvariantCultureIgnoreCase))
break;
Console.WriteLine("Invalid selection. Please try again");
}
You forgot to re-assign the values of prvacrkaVera and ostaloVera in the loop
while (true)
{
if(vera == "Krščanstvo")
{
break;
}
if (vera == "Krscanstvo")
{
break;
}
if (vera == "Hinduizem")
{
break;
}
if (vera == "Islam")
{
break;
}
if (vera == "Budizem")
{
break;
}
Console.WriteLine("Vnesite ustrezno vero");
vera = Console.ReadLine();
prvacrkaVera = vera.Substring(0, 1);
ostaloVera = vera.Substring(1, vera.Length - 1);
prvacrkaVera = prvacrkaVera.ToUpper();
ostaloVera = ostaloVera.ToLower();
vera = prvacrkaVera + ostaloVera;
}
Use a switch statement so you can easily detect when other values are entered
while (true)
{
switch(vera)
{
case "Krscanstvo" :
break;
case "Krščanstvo" :
break;
case "Hinduizem" :
break;
case "Islam" :
break;
case "Budizem" :
break;
default :
break; //exit while loop
break;
}
}
Related
{
bool stayInLoop = true;
while(stayInLoop)
{
Console.WriteLine("Enter Yor Number");
var PlusA = Console.ReadLine();
Console.WriteLine("Enter Yor Number");
var PlusB = Console.ReadLine();
if(PlusA == ';')
{
stayInLoop = false;
break;
}
else if(PlusB == ';')
{
stayInLoop = false;
break;
}
else
{
Console.WriteLine("Answer =");
Console.WriteLine(PlusA + PlusB);
}
}
}
I want to make a plus calculator, I want to let the user type more then 2 numbers, keep asking for PlusC, PlusD, until they type the symbol ; .
For example the user numbers in PlusA PlusB PlusC and in PlusD, he/she type ; so it should print PlusA + PlusB + PlusC
If he type a number in PlusD, it should ask for PlusE, until he/she type ;, it should sum up all the number before
And I want to auto the process, The program will ask for PlusA to PlusZ itself instead of int it my own, how to do that? (I know I am not saying it clearly, coz i can't find better words)
You want to add numbers until the user enters ;. You should use loops for that. Here's the complete solution that uses a for loop:
switch(exp)
{
case "+":
{
var sum = 0;
for(;;)
{
Console.WriteLine("Enter Yor Number");
var line = Console.ReadLine();
if (line == ";") break;
sum += Convert.ToInt32(line);
}
Console.WriteLine(sum);
break;
}
}
Here we repeat the part inside the loop over and over, accumulating entered numbers into sum variable until the user enters ; - that's when we end the loop with break.
Use a while loop:
switch(exp)
{
case "+":
int sum = 0;
string input = "";
do
{
Console.WriteLine("Enter your number:");
input = Console.ReadLine();
if (input != ";")
sum += int.Parse(input);
} while (input != ";");
Console.WriteLine("Answer =" + sum);
break;
}
You are having problems because you should iterate the code until your exit/end condition is met using the while statement.
switch(exp)
{
case "+":
int mySum = 0;
string userInput = "";
while(userInput != ";")
{
Console.WriteLine("Enter number to add (';' to end the sum):");
userInput = Console.ReadLine();
if (userInput != ";")
{
// Would be interesting checking if entered really is an integer, for example Int32.TyParse()
mySum = mySum + Convert.ToInt32(userInput);
}
}
Console.WriteLine("Answer =" + mySum.ToString());
break;
}
Thankyou for your reply, but is there any way to auto the process, The program will ask for PlusA to PlusZ itself instead of int it my own
bool stayInLoop = true;
while(stayInLoop)
Console.WriteLine("Enter Yor Number");
var PlusA = Console.ReadLine();
Console.WriteLine("Enter Yor Number");
var PlusB = Console.ReadLine();
if(PlusA == ';')
{
stayInLoop = false;
break;
}
else if(PlusB == ';')
{
stayInLoop = false;
break;
}
else
{
Console.WriteLine("Answer =");
Console.WriteLine(PlusA + PlusB);
}
}
and when I run this, it run out 'error CS0019' and 'error CS0139'
What you're looking for is a while() loop.
example:
bool stayInLoop = true;
while(stayInLoop) // basically means (stayInLoop == true)
{
var text = Console.ReadLine();
if(text == ';')
{
stayInLoop = false;
break; // break will stop the loop, but you can also change the variable to false to break the loop.
}
}
I don't want to use some sort of goto statement, but I want the user to return to the main menu when the default case is executed. How?? I know this is a simple problem, but there must be lots of newbie who come across something very similar.
static void buycoffee()
{
Double price = 0;
int x = 0;
while (x == 0)
{
Console.WriteLine("Pick a coffee Size");
Console.WriteLine("1: Small");
Console.WriteLine("2: Medium");
Console.WriteLine("3: Large");
int Size = int.Parse(Console.ReadLine());
switch (Size)
{
case 1:
price += 1.20;
break;
case 2:
price += 1.70;
break;
case 3:
price += 2.10;
break;
default:
Console.WriteLine("This option does not exist");
///how to return to the main menu here
break;
}
Console.WriteLine("Would you like to buy more coffee?");
String Response = Console.ReadLine().ToUpper();
if (Response.StartsWith("Y"))
{
Console.Clear();
}
else
{
x += 1;
}
}
Console.WriteLine("The total bill comes to £{0}", price.ToString("0.00"));
}
}
replace your commented line with: continue;
As Nico Schertier said, you can accomplish this with something like the following:
int Size = -1;
while (Size == -1) {
Console.WriteLine("Pick a coffee Size");
Console.WriteLine("1: Small");
Console.WriteLine("2: Medium");
Console.WriteLine("3: Large");
Size = int.Parse(Console.ReadLine());
switch (Size)
{
case 1:
price += 1.20;
break;
case 2:
price += 1.70;
break;
case 3:
price += 2.10;
break;
default:
Size = -1;
Console.WriteLine("This option does not exist");
break;
}
}
Beside #Abion47 and #Dogu Arslan's answers you can also create a function for your menu and also one for your switch.
In this example it will create an infinite loop menu
static void Menu()
{
Console.WriteLine("Menu");
Console.WriteLine("1) Take me to My fancy menu");
}
static void SwitchFunc(string input)
{
switch (input)
{
case "1":
Menu();
string inputB = Console.ReadLine();
SwitchFunc(inputB);
break;
}
}
static void Main(string[] args)
{
Menu();
string input = Console.ReadLine();
SwitchFunc(input);
}
This is a sample of my code. I want to have a 3 second delay before executing the next case (display picturebox). But When I tried using timer/stopwatch, the 3 second delay will only be on the 1st case and case2 will execute the same time as case1 (with no delay).
private void button1_Click(object sender, EventArgs e)
{
string input = (input1.Text).ToString();
char[] letters = input.ToCharArray();
int stringlength = letters.Length;
int length = stringlength - 1;
int state = 1;
int position = 0;
string validation = " ";
switch (state)
{
case 1:
//insert timer here
if (letters[position] == 'a')
{
pictureBox2.Visible = true;
validation = "Invalid";
label1.Text = validation;
break;
}
else if (letters[position] == 'b')
{
if (position == length)
{
validation = "Invalid";
label1.Text = validation;
break;
}
pictureBox2.Visible = true;
position = position + 1;
goto case 2;
}
break;
case 2:
//Insert Timer here
if (letters[position] == 'a')
{
pictureBox3.Visible = true;
if (position == length)
{
validation = "Invalid because it does not end at final state";
label1.Text = validation;
break;
}
position = position + 1;
goto case 3;
}
else if (letters[position] == 'b')
{
if (position == length)
{
validation = "Invalid";
label1.Text = validation;
break;
}
position = position + 1;
goto case 4;
}
break;
}
}
By the way, I can't use Task.Delay or async/await because I use the .Net 4.0 framework.
You can perform this by using:
System.Threading.Thread.Sleep(3000);
So Your code should look like:
private void button1_Click(object sender, EventArgs e)
{
int state = 1;
//some code
switch (state)
{
case 1:
System.Threading.Thread.Sleep(3000);
//some case code
break;
case 2:
System.Threading.Thread.Sleep(3000);
//some case code
break;
default:
System.Threading.Thread.Sleep(3000);
//some default code
break;
}
//rest of the code
}
Just to let You know, there should be other (and better) way to going through this, rather than using switch and this type of GOTO case this and this. Making the code unreadable in future.
Thread.Sleep(3000) you can use
I have this If statement and I would like to move them into Case-Switch
Here is my if Stataments:
if (rResponse.ErrorCode[0] == 0x20 && rResponse.ErrorCode[1] == 0x03)
ErrorMsg = "COMM_FRAME_ERROR";
if (rResponse.ErrorCode[0] == 0x20 && rResponse.ErrorCode[1] == 0x04)
ErrorMsg = "JAM";
if (rResponse.ErrorCode[0] == 0x20 && rResponse.ErrorCode[1] == 0x05)
ErrorMsg = "NO_CARD";
How can I do that?
if (rResponse.ErrorCode[0] == 0x20) {
switch(rResponse.ErrorCode[1]) {
case 0x03:
ErrorMsg = "COMM_FRAME_ERROR";
break;
case 0x04:
ErrorMsg = "JAM";
break;
case 0x05:
ErrorMsg = "NO_CARD";
break;
}
}
If u want both in switch case:
switch(rResponse.Errorcode[0])
case 0x20:
switch(rResponse.ErrorCode[1]) {
case 0x03:
ErrorMsg = "COMM_FRAME_ERROR";
break;
case 0x04:
ErrorMsg = "JAM";
break;
case 0x05:
ErrorMsg = "NO_CARD";
break;
}
break;
Can omit or change the exception,
if (rResponse.ErrorCode[0] == 0x20)
{
switch (rResponse.ErrorCode[1])
{
case 0x03:
ErrorMsg = "COMM_FRAME_ERROR";
break;
case 0x04:
ErrorMsg = "JAM";
break;
case 0x05:
ErrorMsg = "NO_CARD";
break;
default:
throw new InvalidOperationException();
break;
}
}
switch(rResponse.Errorcode[0])
{
case 0x20:
switch(rResponse.ErrorCode[1])
{
case 0x03:
ErrorMsg = "COMM_FRAME_ERROR";
break;
case 0x04:
ErrorMsg = "JAM";
break;
case 0x05:
ErrorMsg = "NO_CARD";
break;
}
break;
}
You can try something like this..
switch (rResponse.ErrorCode[0] + rResponse.ErrorCode[1])
{
case (0x20 + 0x03):
ErrorMsg = "COMM_FRAME_ERROR";
break;
case (0x20 + 0x04):
....
}
though this may not suite all the situations,
Although with the information provided Itay's response might be best. But if this error portion is on a larger scale then maybe something as follows might be worth a go. (Similar approach, just makes it easy to add on.
private string GetError(byte response1, byte response2)
{
var ErrorMessage = "";
switch (response1)
{
case 0x20:
ErrorMessage = ParseCardErrors(response2);
break;
case 0x21:
ErrorMessage = ParseDeviceErrors(response2);
break;
default:
ErrorMessage = "Unknown Error";
}
return ErrorMessage;
}
private string ParseCardErrors(byte response)
{
switch(response)
{
case 0x03:
return "COMM_FRAME_ERROR";
case 0x04:
return "JAM";
case 0x05:
return "NO_CARD";
default:
return "Unknown card Error";
}
}
private string ParseDeviceErrors(byte response)
{
switch(response)
{
case 0x03:
return "COMM_FRAME_ERROR";
case 0x04:
return "Unplugged";
case 0x05:
return "No device";
default:
return "Unknown device Error";
}
}
I might be posting a very diffrent solution this question but it can answer #Robert question:
class Program
{
//This can be included in Seprate class also
public enum ErrorMessages
{
//Store any Values as Key and Pair
// Provide and easy way to update answers
Error1 = 1,
Error2 = 2,
Error3 = 3,
Error4 = 4
}
public static void Main()
{
ICollection<EnumValueDto> list = EnumValueDto.ConvertEnumToList<ErrorMessages>();
foreach (var element in list)
{
Console.WriteLine(string.Format("Key: {0}; Value: {1}", element.Key, element.Value));
}
Console.Read();
/* OUTPUT:
Key: 1; Value: Error1
Key: 2; Value: Error2
Key: 3; Value: Error3
Key: 4; Value: Error4
*/
}
public class EnumValueDto
{
public int Key { get; set; }
public string Value { get; set; }
public static ICollection<EnumValueDto> ConvertEnumToList<T>() where T : struct, IConvertible
{
if (!typeof(T).IsEnum)
{
throw new Exception("Type given T must be an Enum");
}
var result = Enum.GetValues(typeof(T))
.Cast<T>()
.Select(x => new EnumValueDto
{
Key = Convert.ToInt32(x),//values are arbitary here any datatype will work
Value = x.ToString(new CultureInfo("en"))
})
.Where(err => err.Key==3) //Instead of 3 as key here use Response variable instead
.ToList()
.AsReadOnly();
return result;
}
}
}
I recently "finished" a new project except there is a small problem. Im not getting my results back.
This project utilizes c# web services via a SOAP client along with Request and Response Classes. The project is designed to reserve something, in this demo, it reserves a seat in a cinema. However when the data is passed from the windows form client to the web service, nothing comes back. I recently stopped the project from freezing upon execution of the web method.
This is the method that calls the web service (The method signature is only temporary)
public void derp()
{
var client = new SampleServiceSoapClient();
var req = new GetReservationRequest();
req.row = row;
req.seat = seat;
req.name = textNameRequest.Text;
try
{
client.GetReservation(req);
}
catch (Exception err)
{
MessageBox.Show("Server Unavailable");
}
}
I am running this method on a seperate thread to stop crashing. The output of this method is supposed to come back through a response object and then i assign the values of said object to text boxes on the form. However, the data is lost before it returns.
The web method is as follows
[WebMethod]
public GetReservationResponse GetReservation(GetReservationRequest req)
{
object o = HttpContext.Current.Cache["Reservation"];
if(o == null)
{
o = reservedSeat;
}
else
{
reservedSeat = (bool[,])o;
}
GetReservationResponse resp = new GetReservationResponse();
string rowHolder = "A";
int rowRequest = req.row;
int seatCopy = 0;
bool emptySeat = false;
while (rowRequest < 12)
{
for (int seat = req.seat; seat < 16; seat++)
{
if (reservedSeat[req.row, seat])
{
//Loop back
}
else
{
emptySeat = true;
seatCopy = seat;
break;
}
}
if (reservedSeat[req.row, 15])
{
seatCopy = 0;
break;
}
}
switch (rowRequest)
{
case 1: rowHolder = "A";
break;
case 2: rowHolder = "B";
break;
case 3: rowHolder = "C";
break;
case 4: rowHolder = "D";
break;
case 5: rowHolder = "E";
break;
case 6: rowHolder = "F";
break;
case 7: rowHolder = "G";
break;
case 8: rowHolder = "H";
break;
case 9: rowHolder = "I";
break;
case 10: rowHolder = "J";
break;
case 11: rowHolder = "K";
break;
case 12: rowHolder = "L";
break;
default: rowHolder = "None Specified";
break;
}
int x = 0;
if (!reservedSeat[rowRequest, seatCopy])
{
reservedSeat[rowRequest, seatCopy] = true;
seatCopy++;
//resp.row = rowRequest;
x = seatCopy;
seatCopy--;
if (seatCopy.Equals(15))
{
rowRequest++;
}
}
resp.row = rowHolder;
resp.seat = x;
//row++
return resp;
}
I have no clue why the data is being lost before it comes back but some information would be amazing...
Where in this code rowrequest is incremented? It seems to me, that you have infinite loop here:
while (rowRequest < 12)
{
for (int seat = req.seat; seat < 16; seat++)
{
if (reservedSeat[req.row, seat])
{
//Loop back
}
else
{
emptySeat = true;
seatCopy = seat;
break;
}
}
if (reservedSeat[req.row, 15])
{
seatCopy = 0;
break;
}
}