Exclude a value in a comparison - c#

I'm new to writing code and I'm starting with a TicTacToe game to introduce myself. So far I have this:
namespace TicTacToe
{
class Program
{
static void Main(string[] args)
{
string square1 = " ";
string square2 = " ";
string square3 = " ";
string square4 = " ";
string square5 = " ";
string square6 = " ";
string square7 = " ";
string square8 = " ";
string square9 = " ";
bool playerIsX = true;
string symbol = "X";
while (true)
{
Console.WriteLine(" " + square1 + " | " + square2 + " | " + square3);
Console.WriteLine("-----------");
Console.WriteLine(" " + square4 + " | " + square5 + " | " + square6);
Console.WriteLine("-----------");
Console.WriteLine(" " + square7 + " | " + square8 + " | " + square9);
if (playerIsX == true)
{
Console.Write("X enter square: ");
}
else
{
Console.Write("O enter square: ");
}
string square = Console.ReadLine();
if (square == "1")
{
square1 = symbol;
}
else if (square == "2")
{
square2 = symbol;
}
else if (square == "3")
{
square3 = symbol;
}
else if (square == "4")
{
square4 = symbol;
}
else if (square == "5")
{
square5 = symbol;
}
else if (square == "6")
{
square6 = symbol;
}
else if (square == "7")
{
square7 = symbol;
}
else if (square == "8")
{
square8 = symbol;
}
else if (square == "9")
{
square9 = symbol;
}
if (square1 == square2 & square2 == square3)
{
Console.Clear();
Console.WriteLine("You Win!");
Console.ReadLine();
break;
}
else if (square1 == square4 & square4 == square7)
{
Console.Clear();
Console.WriteLine("You Win!");
Console.ReadLine();
break;
}
if (square4 == square5 & square5 == square6)
{
Console.Clear();
Console.WriteLine("You Win!");
Console.ReadLine();
break;
}
if (square7 == square8 & square8 == square9)
{
Console.Clear();
Console.WriteLine("You Win!");
Console.ReadLine();
break;
}
if (square2 == square5 & square5 == square8)
{
Console.Clear();
Console.WriteLine("You Win!");
Console.ReadLine();
break;
}
if (square3 == square6 & square6 == square9)
{
Console.Clear();
Console.WriteLine("You Win!");
Console.ReadLine();
break;
}
if (square1 == square5 & square5 == square9)
{
Console.Clear();
Console.WriteLine("You Win!");
Console.ReadLine();
break;
}
if (square3 == square5 & square5 == square7)
{
Console.Clear();
Console.WriteLine("You Win!");
Console.ReadLine();
break;
}
Console.Clear();
playerIsX = !playerIsX;
if (playerIsX == true)
{
symbol = "X";
}
else
{
symbol = "O";
}
}
}
}
}
I know it's beefy but I'm only trying to get a basic understanding so I can move on from there. Currently for the winning I compare three values, but since they're all spaces, at the start of the game multiple possibilities already trigger the win. Is there a way to exclude a value, say space?
Thanks.

In your specific situation, you have a common field in each if statement - a field is always evaluated twice as such:
if (square4 == square5 & square5 == square6)
{
Console.Clear();
Console.WriteLine("You Win!");
Console.ReadLine();
break;
}
square5 is evaluated against both square4, and square6, so we can definitely argue that if square5 is not equal to " ", this statement will not pass.
From there, you could easily just implement a quick check:
if (square4 == square5 & square5 == square6 && square5 != " ")
{
Console.Clear();
Console.WriteLine("You Win!");
Console.ReadLine();
break;
}
I would highly suggest you look into developing a more readable, and elegant piece of code for what you're doing though, good luck on your learning journey!

The quickest (not best) way to do it would be to check for a space in your comparison. That means this
if (square1 == square2 & square2 == square3)
would turn into
if (square1 == square2 & square2 == square3 & square3 != " ")

Related

Choosing in menu wirh arrows on keyboard (C#)

I am trying to make a simple menu where I can choose with the arrows on the keyboard. I can run the code and the program doesn't give any errors, however I can not choose with the arrows and nothing happens if I press Enter, the choice always remains on the first choice (New customer). That will say, It always stays like this:
Hello and welcome! please choose type of registration:
*New customer <--
New staff
Service
Reparation
Garantie
My code this far is:
using System;
namespace uppdrag_2.cs
{
class Program
{
static void Main(string[] args)
{
string[] menuOptions = new string[] {"New customer\t", "New staff\t", "Serivce\t", "Reparation", "Garantie" };
int menuSelect = 0;
while (true)
{
Console.Clear();
Console.CursorVisible = false;
Console.WriteLine("Hello and welcome! Please choose type of registration:");
if (menuSelect == 0)
{
Console.WriteLine("* " + menuOptions[0] + "<--");
Console.WriteLine(menuOptions[1]);
Console.WriteLine(menuOptions[2]);
Console.WriteLine(menuOptions[3]);
Console.WriteLine(menuOptions[4]);
Console.ReadLine();
}
else if (menuSelect == 1)
{
Console.WriteLine(menuOptions[0]);
Console.WriteLine("* " + menuOptions[1] + "<--");
Console.WriteLine(menuOptions[2]);
Console.WriteLine(menuOptions[3]);
Console.WriteLine(menuOptions[4]);
Console.ReadLine();
}
else if (menuSelect == 2)
{
Console.WriteLine(menuOptions[0]);
Console.WriteLine(menuOptions[1]);
Console.WriteLine("* " + menuOptions[2] + "<--");
Console.WriteLine(menuOptions[3]);
Console.WriteLine(menuOptions[4]);
Console.ReadLine();
}
else if (menuSelect == 3)
{
Console.WriteLine(menuOptions[0]);
Console.WriteLine(menuOptions[1]);
Console.WriteLine(menuOptions[2]);
Console.WriteLine("* " + menuOptions[3] + "<--");
Console.WriteLine(menuOptions[4]);
Console.ReadLine();
}
else if (menuSelect == 4)
{
Console.WriteLine(menuOptions[0]);
Console.WriteLine(menuOptions[1]);
Console.WriteLine(menuOptions[2]);
Console.WriteLine(menuOptions[3]);
Console.WriteLine("* " + menuOptions[4] + "<--");
Console.ReadLine();
}
var keyPressed = Console.ReadKey();
if (keyPressed.Key == ConsoleKey.DownArrow && menuSelect != menuOptions.Length - 1)
{
menuSelect++;
}
else if (keyPressed.Key == ConsoleKey.UpArrow && menuSelect >= 1)
{
menuSelect--;
}
else if (keyPressed.Key == ConsoleKey.Enter)
{
switch (menuSelect)
{
case 0:
Newcustomer();
break;
case 1:
NewStaff();
break;
case 2:
Service();
break;
case 3:
Reparation();
break;
case 4:
Garantie();
break;
}
}
}
}
public static void Newcustomer(){
Console.WriteLine("You have chosen to registrate a new customer!");
Console.WriteLine("Please enter name of customer:");
string name = Console.ReadLine();
Console.WriteLine("Enter car brand:");
string carBrand = Console.ReadLine();
Console.WriteLine("Enter model of car");
string model = Console.ReadLine();
Console.WriteLine("Enter year model");
string yearModel = Console.ReadLine();
Console.WriteLine("Enter how many km the car has been driven");
string km = Console.ReadLine();
Console.WriteLine("Registration compleated!");
Console.WriteLine("You have registered a new customer! You have registrered" + " " + name + " " + "with the carbrand" + carBrand + " " + "of model" + " " + model + " " + "form year" + " " + yearModel + " " + "That has been driven" + " " + km + "km.");
Console.ReadKey();
}
public static void NewStaff(){
Console.WriteLine("You have chosen to registrer a new staffmember!");
Console.WriteLine("Please enter name of staffmember:");
string staffName = Console.ReadLine();
Console.WriteLine("Enter age:");
string ageStaff = Console.ReadLine();
Console.WriteLine("Enter work position of the new staffmember:");
string position = Console.ReadLine();
Console.WriteLine("Enter type of contract:");
string contract = Console.ReadLine();
Console.WriteLine("Enter date of the workers first day:");
string start = Console.ReadLine();
Console.WriteLine("Enter date of the workrs last day:");
string end = Console.ReadLine();
Console.WriteLine("Registration compleated!");
Console.WriteLine("You have registrered a new staffmember! The following information has been registered:\t" + "name: " + staffName + "\t" + "age: " + ageStaff + "\t" + "position: " + position + "\t" + "Contract: " + contract + "\t" + "First day: " + start + "\t" + "Last day: " + end);
Console.ReadKey();
}
public static void Service(){
Console.WriteLine("Please enter type of service:");
string service = Console.ReadLine();
Console.WriteLine("Enter the name of an registered customer. If customer is not already registered, please press Enter to return to menu and choose `New customer`");
string customerservice = Console.ReadLine();
Console.WriteLine("Enter staffmember responsible for this matter. If staffmember is new, please press Enter to return to the menu and choose ``New staff`");
string servicestaff = Console.ReadLine();
Console.WriteLine("Enter staring day of service:");
string serviceStart = Console.ReadLine();
Console.WriteLine("Enter deadline of servicematter:");
string deadline = Console.ReadLine();
Console.WriteLine("Service matter registrered!");
Console.WriteLine("Following information has been registrered:\t" + "Service matter: " + service + "\t" + "Customer: " + customerservice + "\t" + "Staff member responsible: " + servicestaff + "\t" + "Startdate of service matter: " + serviceStart + "\t" + "Deadline: " + deadline);
Console.ReadKey();
}
public static void Reparation(){
Console.WriteLine("You have choosen to registrer a reparation matter!");
Console.ReadLine();
Console.ReadKey();
}
public static void Garantie(){
Console.WriteLine("You have choosen to registrate a garantie matter!");
Console.WriteLine();
Console.ReadKey();
}
}
}
Anyone who could help me figure out what I`ve done wrong?
You can shorten your menu code quite a bit by using a for loop and a ternary if statement:
static void Main(string[] args)
{
string[] menuOptions = new string[] { "New customer\t", "New staff\t", "Serivce\t", "Reparation\t", "Garantie\t" };
int menuSelect = 0;
while (true)
{
Console.Clear();
Console.CursorVisible = false;
Console.WriteLine("Hello and welcome! Please choose type of registration:");
for (int i = 0; i < menuOptions.Length; i++)
{
Console.WriteLine((i == menuSelect ? "* " : "") + menuOptions[i] + (i == menuSelect ? "<--" : ""));
}
var keyPressed = Console.ReadKey();
if (keyPressed.Key == ConsoleKey.DownArrow && menuSelect != menuOptions.Length - 1)
{
menuSelect++;
}
else if (keyPressed.Key == ConsoleKey.UpArrow && menuSelect >= 1)
{
menuSelect--;
}
else if (keyPressed.Key == ConsoleKey.Enter)
{
switch (menuSelect)
{
case 0:
Newcustomer();
break;
case 1:
NewStaff();
break;
case 2:
Service();
break;
case 3:
Reparation();
break;
case 4:
Garantie();
break;
}
}
}
}
public static void Newcustomer()
{
Console.WriteLine("New Customer ...");
Console.Write("Press Enter to Continue");
Console.ReadLine();
}
public static void NewStaff()
{
Console.WriteLine("New Staff ...");
Console.Write("Press Enter to Continue");
Console.ReadLine();
}
public static void Service()
{
Console.WriteLine("Service ...");
Console.Write("Press Enter to Continue");
Console.ReadLine();
}
public static void Reparation()
{
Console.WriteLine("Reparation ...");
Console.Write("Press Enter to Continue");
Console.ReadLine();
}
public static void Garantie()
{
Console.WriteLine("Garantie ...");
Console.Write("Press Enter to Continue");
Console.ReadLine();
}
}
It works fine for me:

Going back/forward to a command in C#

Console.WriteLine('What is your name, traveler?');
string mainName = Console.ReadLine();
Console.WriteLine('So, your name is ' + mainName + ' ? y/n');
char ans = Console.ReadKey;
if (ans == y)
{
Console.WriteLine('Nice, let me introduce myself now.');
}
else if(ans == n)
{
}
else
{
Console.WriteLine('Please insert either y or n.');
}
In the code above, how can I make it so that the else if statement will return to the third line and the else statement will return to the first line of the code and continue running from there?
You can try to use do....While(true) loop
Console.WriteLine("What is your name, traveler?");
string mainName = Console.ReadLine();
Console.WriteLine("So, your name is " + mainName + " ? y/n");
do
{
var ans = Console.ReadKey(true).Key;
if (ans == ConsoleKey.Y)
{
Console.WriteLine("Nice, let me introduce myself now.");
break;
}
else if (ans == ConsoleKey.N)
{
break;
}
Console.WriteLine("Please insert either y or n.");
} while (true);
Note
I would use Console.ReadKey(true).Key to get keyboard input value,because it's enum.

Do loop is looping when I don't want it to in my 'game choices' program

So I'm stuck again, I created a 'game choices' program that allows users to choose their 'skill' level. I have wrote all the code but the do loop on line 24 is causing issues. It will not loop when I choose a higher skill level than 4 or when I type 'n' in "Is this what you want (y/n)". Here is the code:
class Program
{
static void Main(string[] args)
{
string name;
int one = 1, two = 2, three = 3, four = 4;
int answer;
int tripalarm = 0;
string verification;
Console.WriteLine("What is your name?");
name = Convert.ToString(Console.ReadLine());
Console.WriteLine(name + ", there are 4 skill levels in this game:");
Console.WriteLine("1. Advanced" + Environment.NewLine + "2. Experienced" + Environment.NewLine + "3. Average"
+ Environment.NewLine + "4. Novice");
do
{
answer = 0;
Console.WriteLine("Which skill level do you choose?");
answer = Convert.ToInt32(Console.ReadLine());
if (answer >= 5)
{
Console.WriteLine("Sorry " + name + " you should choose between 1 and 4:");
}
else if (answer <= 4)
{
if (answer == one)
{
Console.WriteLine("Thank you " + name + ", you have choosen level one");
Console.WriteLine("Is this what you want? (y/n)");
verification = Convert.ToString(Console.ReadLine());
if (verification == "y")
{
Console.WriteLine("Good " + name + " you have chosen level one you can now start the game!");
}
else
{
tripalarm++;
}
}
else if (answer == two)
{
Console.WriteLine("Thank you " + name + ", you have choosen level two");
Console.WriteLine("Is this what you want? (y/n)");
verification = Convert.ToString(Console.ReadLine());
if (verification == "y")
{
Console.WriteLine("Good " + name + " you have chosen level two you can now start the game!");
}
else
{
tripalarm++;
}
}
else if (answer == three)
{
Console.WriteLine("Thank you " + name + ", you have choosen level three");
Console.WriteLine("Is this what you want? (y/n)");
verification = Convert.ToString(Console.ReadLine());
if (verification == "y")
{
Console.WriteLine("Good " + name + " you have chosen level three you can now start the game!");
}
else
{
tripalarm++;
}
}
else if (answer == four)
{
Console.WriteLine("Thank you " + name + ", you have choosen level four");
Console.WriteLine("Is this what you want? (y/n)");
verification = Convert.ToString(Console.ReadLine());
if (verification == "y")
{
Console.WriteLine("Good " + name + " you have chosen level four you can now start the game!");
}
else
{
tripalarm++;
}
}
}
} while (tripalarm == 0);
}
}
I have tried almost everything, changing the while value at the bottom does not change anything. It still loops when it is not supposed to.
Much help would be appreciated, thanks.
This simplifies your code a bit and should correct the bug:
static void Main(string[] args)
{
var levelSelected = false;
var answer = 0;
Console.WriteLine("What is your name?");
string name = Console.ReadLine();
Console.WriteLine($"{name}, there are 4 skill levels in this game:");
Console.WriteLine("1. Advanced");
Console.WriteLine("2. Experienced");
Console.WriteLine("3. Average");
Console.WriteLine("4. Novice");
while (!levelSelected)
{
Console.WriteLine("Which skill level do you choose?");
answer = Convert.ToInt32(Console.ReadLine());
switch (answer)
{
case 1:
case 2:
case 3:
case 4:
Console.WriteLine($"Thank you {name}, you have choosen level {answer}");
Console.WriteLine("Is this what you want? (y/n)");
levelSelected = Console.ReadLine() == "y";
break;
default:
Console.WriteLine($"Sorry {name} you should choose between 1 and 4:");
break;
}
}
Console.WriteLine($"Good {name} you have chosen level {answer} you can now start the game!");
var x = Console.ReadLine();
}
Note it still doesn't check that the user enters an integer for the level (if they don't it will cause an error) and anything other that "y" is treated as "n".

C# Loop back to a previous part of code

//Gender Creation:
while (correct == 0)
{
do
{
Console.Clear();
Console.WriteLine("Please choose a gender from the options below: ");
Console.WriteLine("Male|Female|Random");
Console.Write("Input: ");
Gender = Console.ReadLine().ToUpper();
if (Gender == "MALE")
{
Console.WriteLine("Is this the gender you wish your character to be? Enter Yes/No: ");
Console.Write("Input: ");
Input = Console.ReadLine().ToUpper();
if (Input == "YES")
{
correct = 1;
}
else if (Input == "NO")
{
correct = 0;
}
}
else if (Gender == "FEMALE")
{
Console.WriteLine("Is this the gender you wish your character to be? Enter Yes/No: ");
Console.Write("Input: ");
Input = Console.ReadLine().ToUpper();
if (Input == "YES")
{
correct = 1;
}
else if (Input == "NO")
{
correct = 0;
}
}
else if (Gender == "RANDOM")
{
correct = 2;
}
else
{
Console.WriteLine("ERROR, Please try again.");
Gender = Console.ReadLine().ToUpper();
}
} while (correct == 0);
//Random Gender Creation:
if (correct == 2)
{
do
{
if (randgender == 1)
{
Console.WriteLine("The gender: MALE was randomly chosen");
Console.WriteLine("Is this the gender you wish your character to be? Enter Yes/No: ");
Console.Write("Input: ");
Input = Console.ReadLine().ToUpper();
if (Input == "YES")
{
correct = 1;
Gender = "MALE";
}
else if (Input == "NO")
{
correct = 2;
}
}
else if (randgender == 2)
{
Console.WriteLine("The gender: FEMALE was randomly chosen");
Console.WriteLine("Is this the race you wish your character to be? Enter Yes/No: ");
Console.Write("Input: ");
Input = Console.ReadLine().ToUpper();
if (Input == "YES")
{
correct = 1;
Gender = "FEMALE";
}
else if (Input == "NO")
{
correct = 2;
}
}
} while (correct == 2);
correct = 0;
}
break;
}
When correct = 2 then the gender is being randomly generated, if the user inputs no when being asked if they are happy with the gender the code will just loop the random gender generator over and over constantly saying that the random gender is the same every time as the random number is never changing however when correct = 0 the code will just proceed when no is inputted and when the gender is printed it is just printed as RANDOM as that is the option the user initially chose.
How can I make it go back to the first do while loop to ask the user what gender they want their character to be?
As theMayer suggested, you'll need to break down your app into smaller pieces. There are also a few concepts that you may need to tackle before you can write C#, as such.
This example might help you get a little further along, as it illustrates several ways of achieving better control flow:
static void Main(string[] args)
{
Console.Clear();
var choosenGender = "";
var wasChoiceConfirmed = false;
while (wasChoiceConfirmed == false)
{
choosenGender = PromptForGender();
switch (choosenGender)
{
case "RANDOM":
var randomGender = GenerateRandomGender();
wasChoiceConfirmed = PromptForGenderConfirmation(randomGender, true);
break;
case "MALE":
case "FEMALE":
wasChoiceConfirmed = PromptForGenderConfirmation(choosenGender);
break;
default:
Console.WriteLine("Error, please try again. \n");
break;
}
}
}
static string PromptForGender()
{
Console.Write(
"\nPlease choose a gender from the options below: \n" +
"Male|Female|Random \n" +
"Input:");
return Console.ReadLine().Trim().ToUpper();
}
static bool PromptForGenderConfirmation(string gender, bool wasRandom = false)
{
var randomVerbiage = wasRandom ? "randomly " : "";
Console.Write(
$"\nThe gender: {gender} was {randomVerbiage}chosen \n" +
"Is this the gender you wish your character to be? Enter Yes/No: \n" +
"Input: ");
var confirmed = Console.ReadLine().Trim().ToUpper();
return confirmed == "YES";
}
static string GenerateRandomGender()
{
var randomNumber = new Random();
return randomNumber.Next(0, 1) == 0 ? "FEMALE" : "MALE";
}
I refactored your code so it helps me understand it better. This gives you the result you want and you don't need all those nested loops.
public class Program
{
public static void AskFirstQuestion()
{
Console.Clear();
Console.WriteLine("Please choose a gender from the options below: ");
Console.WriteLine("Male|Female|Random");
Console.Write("Input: ");
var gender = Console.ReadLine()?.ToUpper();
if (gender == "MALE" || gender == "FEMALE")
{
HandleGenderSelection(gender);
}
else if (gender == "RANDOM")
{
HandleRandom();
}
}
private static void HandleRandom()
{
var randomGender = GenerateRandomGender();
Console.WriteLine($"The gender: {randomGender} was randomly chosen");
Console.WriteLine("Is this the race you wish your character to be? Enter Yes/No: ");
Console.Write("Input: ");
var input = Console.ReadLine()?.ToUpper();
switch (input)
{
case "YES":
Console.WriteLine("OK");
break;
case "NO":
AskFirstQuestion();
break;
}
}
private static string GenerateRandomGender()
{
//Have you logic to randomly create gender
return "MALE";
}
private static void HandleGenderSelection(string gender)
{
Console.WriteLine("Is this the gender you wish your character to be? Enter Yes/No: ");
Console.Write("Input: ");
var input = Console.ReadLine()?.ToUpper();
if (input == "YES")
{
Console.WriteLine("OK!");
}
else if (input == "NO")
{
AskFirstQuestion();
}
}
static void Main(string[] args)
{
AskFirstQuestion();
}
}

Option yes/no C# Console

I'm creating a C# program for the Currency Converter by console.
At the end I would to insert "Continue? (yes/no)". Here the user have to chose. I've tried this but it doesn't work
float Dollaro = 1.32f, Euro;
float Cambio;
string EuroStr;
Console.Write("Euro: ");
EuroStr = Console.ReadLine();
Euro = float.Parse(EuroStr);
Cambio = Dollaro * Euro;
Console.WriteLine("Dollaro: " + Cambio);
Console.WriteLine("Vuoi continuare? (yes/no)");
Console.ReadLine();
string risposta = Console.ReadLine();
do
{
if (risposta.Equals("Y"))
{
Console.WriteLine("Yes");
break;
}
else if (risposta.Equals("N"))
{
Console.WriteLine("No");
break;
}
} while (risposta == "N");
you want something like that
float Dollaro = 1.32f, Euro;
float Cambio;
string EuroStr;
do
{
Console.Write("Euro: ");
EuroStr = Console.ReadLine();
Euro = float.Parse(EuroStr);
Cambio = Dollaro * Euro;
Console.WriteLine("Dollaro: " + Cambio);
Console.WriteLine("Vuoi continuare? (yes/no)");
Console.ReadLine();
string risposta = Console.ReadLine();
if (risposta.Equals("Y"))
{
Console.WriteLine("Yes");
break;
}
else if (risposta.Equals("N"))
{
Console.WriteLine("No");
break;
}
} while (risposta == "N");
but that's just a sample, you need to give more information so i'll give you better example. what does your code supposed to do? what other option does the user have? and so on
float Dollaro = 1.32f, Euro, Cambio;
string EuroStr;
ConsoleKeyInfo risposta;
do
{
Console.Write ( "Euro: " );
EuroStr = Console.ReadLine ();
bool result = Single.TryParse ( EuroStr, out Euro );
if ( result )
{
Cambio = Dollaro * Euro;
Console.WriteLine ( "Dollaro: " + Cambio );
} else {
Console.WriteLine ( "Please enter a number" );
}
bool check = false;
do {
Console.Write ( "\nVuoi continuare? (yes/no) " );
risposta = Console.ReadKey ( true );
check = !( ( risposta.Key == ConsoleKey.Y ) || ( risposta.Key == ConsoleKey.N ) );
} while ( check );
switch ( risposta.Key )
{
case ConsoleKey.Y: Console.WriteLine ( "Yes" ); break;
case ConsoleKey.N: Console.WriteLine ( "No" ); break;
}
} while ( risposta.Key != ConsoleKey.N );
I've changed some things:
if I enter a character for the Euro - FormatException msdn. So I've added a TryParse();
I've changed the response from string to ConsoleKeyInfo msdn - this makes the check for "Y" or "N" easier and I think clearer, and there is no need to cast the user input with ToLower() msdn and compare it with a string;
also a check if the user presses "Y" or "N", while the input is different, the same message will appear - Console.Write ( "\nVuoi continuare? (yes/no) " );
In general you should filter all data\info ( whatever ) comes from the user, to avoid exception.
You should move code where you do operation to do while loop.
Try this:
static void Main(string[] args)
{
float Dollaro = 1.32f, Euro;
float Cambio;
string EuroStr;
string risposta = "Y";
do
{
Console.Write("Euro: ");
EuroStr = Console.ReadLine();
Euro = float.Parse(EuroStr);
Cambio = Dollaro * Euro;
Console.WriteLine("Dollaro: " + Cambio);
Console.WriteLine("Vuoi continuare? (yes/no)");
risposta = Console.ReadLine();
if (risposta.Equals("Y"))
{
Console.WriteLine("Yes");
}
else if (risposta.Equals("N"))
{
Console.WriteLine("No");
}
} while (risposta == "Y");
}
This should fix your problem:
And you should make your variable "risposta" ToLower so that it doesnt matter if you type a small or big letter (y or Y)
float Dollaro = 1.32f, Euro;
float Cambio;
string EuroStr;
string risposta = "Y";
do
{
Console.Write("Euro: ");
EuroStr = Console.ReadLine();
Euro = float.Parse(EuroStr);
Cambio = Dollaro * Euro;
Console.WriteLine("Dollaro: " + Cambio);
Console.WriteLine("Vuoi continuare? (yes/no)");
risposta = Console.ReadLine();
if (risposta.Equals("Y"))
{
Console.WriteLine("Yes");
}
else if (risposta.Equals("N"))
{
Console.WriteLine("No");
}
} while (risposta.ToLower() == "y");
You need to 'read' answer to be able to test it.
answer = Console.ReadLine();
You can try this, you can also add "else" statements for other key presses.
string key = "";
do
{
Console.Write("Enter Username: ");
username = Console.ReadLine();
Console.Write("Is this correct? (Y/N): ");
key = Console.ReadLine();
if (key.Equals("Y") | key.Equals("y"))
{
break;
}
} while (true);
Try this code:
int num1, num2;
char oPt;
string Count;
do
{
Console.WriteLine("Enter 1st Value");
num1 = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("Enter 2nd Value : ");
num2 = Convert.ToInt32(Console.ReadLine());
Console.WriteLine(" + - * / ");
oPt = Convert.ToChar(Console.ReadLine());
if (oPt == '-')
{
Console.WriteLine("Result: " + (num1 - num2));
}
else if (oPt == '+')
{
Console.WriteLine("Result: " + (num1 + num2));
}
else if (oPt == '*')
{
Console.WriteLine("Result: " + (num1 * num2));
}
else if (oPt == '/')
{
Console.WriteLine("Result: " + (num1 / num2));
}
do
{
Console.WriteLine("Do you wish to calculate another? Yes (y) or No (n): ");
Count = Console.ReadLine();
var CountLower = Count?.ToLower();
if ((CountLower == "y") || (CountLower == "n"))
break;
} while (true );
} while (Count != "n");
}

Categories