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.
Related
Hello I'm new to C# and started learning it yesterday with some Java and Python knowledge. I tried to make a calculator but it isn't working as expected.
The code is:
using System;
namespace LolCS{
class Program{
static void Main(){
//variables and objects
Program proj = new Program();
double solution = 0;
string operation;
double input1 = 0;
double input2 = 0;
//take inputs for input 1,2 and which operation to use
Console.WriteLine("Welcome to this calculator, let's get started\n"+
"Please input your operations\n");
double.TryParse(proj.get_input("in1"), out input1);
operation = proj.get_input("op");
double.TryParse(proj.get_input("in2"), out input2);
//call function which does the math and assign result to variable solution
solution = proj.domath(operation, input1, input2);
//print solution
Console.WriteLine(input1+operation+input2+" = "+solution);
if (Console.ReadLine() == "r") { Main(); }
}
//function to do the math according to the given operation
double domath(string oper, double in1, double in2){
double solu = 0;
switch(oper){
case "+":
solu = in1 + in2;
break;
case "-":
solu = in1-in2;
break;
case "*":
solu = in1 * in2;
break;
case "/":
solu = in1 / in2;
break;
}
return solu;
}
//gets values for the variables
string get_input(string in_type){
string gon_ret = "";
switch(in_type){
case "in1":
Console.WriteLine("Input 1: ");
gon_ret = Console.ReadLine();
break;
case "in2":
Console.WriteLine("Input 2: ");
gon_ret = Console.ReadLine();
break;
case "op":
Console.WriteLine("Operation: ");
gon_ret = Console.ReadLine();
if (!(gon_ret == "+") && !(gon_ret == "-") && !(gon_ret == "*") && !(gon_ret == "/")){
Console.WriteLine(gon_ret+" Not Valid, try again");
get_input("op");
}
break;
}
return gon_ret;
}
}
}
The problem is with this line of code:
case "op":
Console.WriteLine("Operation: ");
gon_ret = Console.ReadLine();
if (!(gon_ret == "+") && !(gon_ret == "-") && !(gon_ret == "*") && !(gon_ret == "/")){
Console.WriteLine(gon_ret+" Not Valid, try again");
get_input("op");
}
break;
It is expected to check if the input for operation is different than +,-,* or / and if it is it should print "Not Valid" and repeat the input for the operation. That works as expected if the input is correct the first time but if the correct input is given on the second try or later, the false input is returned. Example output:
Welcome to this calculator, let's get started
Please input your operations
Input 1:
2
Operation:
p
p Not Valid, try again
Operation:
+
Input 2:
3
2p3 = 0
Sorry if it is a stupid mistake but I'm still learning. Thanks for the help!
You are doing a recursive operation with get_input("op") The function works fine but you are not returning the results of the new get_input("op") call. You are returning the invalid string produce from the original call.
case "op":
Console.WriteLine("Operation: ");
gon_ret = Console.ReadLine();
if (!(gon_ret == "+") && !(gon_ret == "-") && !(gon_ret == "*") && !(gon_ret == "/")){
Console.WriteLine(gon_ret+" Not Valid, try again");
//Return here as the current call is invalid
return get_input("op");
}
break;
//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();
}
}
After searching for a Solution with a do-while Loop, I'm now stuck and this point, and just cant figure out what I am doing wrong.
static void StartUp()
{
bool confirmChoice = false;
Console.WriteLine("Hey, Enter your Character Name!");
string name = Console.ReadLine();
do
{
Console.WriteLine("Is " + name + " correct? (y) or would you like to change it (n)?");
string input = Console.ReadLine();
if (input == "n")
{
Console.WriteLine("Allright, enter your new Name then!");
name = Console.ReadLine();
break;
}
else
{
confirmChoice = true;
}
}while(confirmChoice);
}
Your code is almost right - all you need to do is inverting the condition of your do/while loop to while (!confirmChoice)
However, you could do better than that: make a forever loop, and use break to exit it:
while (true) {
Console.WriteLine("Please, Enter your Character Name!");
string name = Console.ReadLine();
Console.WriteLine("Is " + name + " correct? (y) or would you like to change it (n)?");
string input = Console.ReadLine();
if (input == "y") {
break;
}
}
This is a common solution for situations when the decision to exit is made in the middle of the loop body.
you should change the termination condition for your loop
it should be while(!confirmChoice);
and you should change the break; line to continue;
Your Condition is wrong it should be while(confirmChoice==false) and don't use break;
static void StartUp()
{
bool confirmChoice = false;
Console.WriteLine("Hey, Enter your Character Name!");
string name = Console.ReadLine();
do
{
Console.WriteLine("Is " + name + " correct? (y) or would you like to change it (n)?");
string input = Console.ReadLine();
if (input == "n")
{
Console.WriteLine("Allright, enter your new Name then!");
name = Console.ReadLine();
}
else
{
confirmChoice = true;
}
}while(confirmChoice==false);
}
I deliberately designed this code, and i can't use it. Can i override this fail-safe?
do // Checks if the chosen name is also the right name
{
string test;
Console.Write("Are you sure " + temp + " is the right name? (y/n)\n");
test = Console.ReadLine();
Console.Write("\n");
if (test.ToLower() == "y")
{
nameIsRight = true;
return temp;
}
else if (test.ToLower() == "n")
{
Console.Write("What is your name then?\n");
temp = Console.ReadLine();
}
Console.Write("\n");
} while (nameIsRight == false);
You should add return statement after this loop:
do // Checks if the chosen name is also the right name
{
//...
}while (!nameIsRight);
return something;
UPDATE: As #hvd stated, you always return from loop. So, possibly throwing exception is a better way here.
UPDATE2: I think best solution is to get rid of boolean flag and inner return statement:
do // Checks if the chosen name is also the right name
{
Console.Write("Are you sure " + temp + " is the right name? (y/n)\n");
key = Console.ReadKey().Key;
Console.Write("\n");
if (key == ConsoleKey.N)
{
Console.Write("What is your name then?\n");
temp = Console.ReadLine();
}
Console.Write("\n");
} while (key != ConsoleKey.Y);
return temp;
Just learn to write better readable (and maintainable) code.
// Ask what you have to ask before the loop
Console.Write("Enter the name: \n");
string result = Console.ReadLine();
while(true)
{
Console.Write("Are you sure " + result + " is the right name? (y/n)\n");
string test = Console.ReadLine();
Console.Write("\n");
if (test.ToLower() == "y")
{
// it will exit the loop
break;
}
// when loop is not exited, keep asking until user answers with "y"
Console.Write("What is your name then?\n");
result = Console.ReadLine();
Console.Write("\n");
};
// result will always contain the latest input, as it's not possible for the user to leave
// except closing the application
return result;
This way you will never get in such a situation and the code is more readable, because you clearly see the break when the loop leaves and you don't need any returns inside the loop at all and you don't need to manage a loop condition (while (nameIsRight == false)).
I would rather do something like this:
EDIT: Corrected code.
do // Checks if the chosen name is also the right name
{
string test;
Console.Write("Are you sure " + temp + " is the right name? (y/n)\n");
test = Console.ReadLine();
Console.Write("\n");
if (test.ToLower() == "y")
{
nameIsRight = true;
}
else if (test.ToLower() == "n")
{
Console.Write("What is your name then?\n");
temp = Console.ReadLine();
continue;
}
else
{
Console.WriteLine("Incorrect input!!!");
continue;
}
} while (nameIsRight == false);
return temp;
You should not be returning your variable from inside the loop, but only setting the condition to true or false.
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");
}