C# Console application crashing before if statement can run - c#

static void Main(string[] args)
{
Console.ForegroundColor = ConsoleColor.Green;
Console.WriteLine("1. SHC ");
int UserInput1 = Console.Read();
if (UserInput1 == 1)
{
Console.WriteLine("Mass (kg): ");
int shcmass = Console.Read();
Console.WriteLine("Specific Heat Capactiy (J/Kg/°C): ");
int shcshc = Console.Read();
Console.WriteLine("Temperature Difference (△Ø): ");
int shctemp = Console.Read();
int shcfinal = shcmass * shcshc * shctemp;
Console.WriteLine("Energy: " + shcfinal);
}
This is the code I am using within a small console application. I don't know if I am missing something but every time I run it, the first bit works where it says "1. SHC" and gives time for the user input. But once entered the console application dies and I cannot figure out why.

There's nothing stopping the console application to close, add a Console.ReadLine() at the end of your mainloop. I'd recommend using ReadLine() over reads for other input as well, but it would depend on your needs. If you see from the "Remarks" section of the Console.Read documentation it's preferable to use ReadLine()
e.g.
static void Main(string[] args)
{
Console.ForegroundColor = ConsoleColor.Green;
Console.WriteLine("1. SHC ");
int UserInput1 = int.Parse(Console.ReadLine());
if (UserInput1 == 1)
{
Console.WriteLine("Mass (kg): ");
int shcmass = int.Parse(Console.ReadLine());
Console.WriteLine("Specific Heat Capactiy (J/Kg/°C): ");
int shcshc = int.Parse(Console.ReadLine());
Console.WriteLine("Temperature Difference (△Ø): ");
int shctemp = int.Parse(Console.ReadLine());
int shcfinal = shcmass * shcshc * shctemp;
Console.WriteLine("Energy: " + shcfinal);
}
Console.ReadLine();
}

Console.Read() returns
The next character from the input stream, or negative one (-1) if
there are currently no more characters to be read.
https://msdn.microsoft.com/en-us/library/system.console.read(v=vs.110).aspx
You will need
ch = Convert.ToChar(x);
Excerpt:
class Sample
{
public static void Main()
{
string m1 = "\nType a string of text then press Enter. " +
"Type '+' anywhere in the text to quit:\n";
string m2 = "Character '{0}' is hexadecimal 0x{1:x4}.";
string m3 = "Character is hexadecimal 0x{0:x4}.";
char ch;
int x;
//
Console.WriteLine(m1);
do
{
x = Console.Read();
try
{
ch = Convert.ToChar(x);
if (Char.IsWhiteSpace(ch))
{
Console.WriteLine(m3, x);
if (ch == 0x0a)
Console.WriteLine(m1);
}
else
Console.WriteLine(m2, ch, x);
}
catch (OverflowException e)
{
Console.WriteLine("{0} Value read = {1}.", e.Message, x);
ch = Char.MinValue;
Console.WriteLine(m1);
}
} while (ch != '+');
}
}

I've had similar issues before. When using Console.Read() after Console.WriteLine() you'll end up reading '\r' which is what causes the crash I believe. Try using Console.ReadKey() instead.

Related

C# How to keep do-while loop asking the same question until enter pressed

I am a beginner in C# programming and trying to code an app that reads the user input using a do-while loop, however, the loop doesn't continue executing when the user answers the question. I only want the loop to stops when enter is pressed
This is what I have done so far
Thanks in advance!
//call method to read a text, calculate and display the num of chars
private void ShowStringLength() {
ConsoleKeyInfo cki;
do
{
Console.WriteLine("Let me calculate the length of strings for you!");
Console.WriteLine("Give me text of any length, or press ENTER to exit!");
Console.Write("Enter a string : ");
String str = Console.ReadLine();
Console.WriteLine(str.ToUpper());
int len = str.Length;
Console.WriteLine("Numer of Chars is : " + len);
//Reads “Enter” from the keyboard to exit the app
cki = Console.ReadKey();
Console.Write("OK. You pressed Enter. See you agian!");
} while (cki.Key != ConsoleKey.Enter);
The cki = Console.ReadKey(); waits for any key input, not just enter. This makes the text "OK. You pressed Enter. See you agian!" show even if you actually pressed another key.
You could instead check the entered string, and exit the loop if it is empty. Example:
while (true)
{
Console.WriteLine("Let me calculate the length of strings for you!");
Console.WriteLine("Give me text of any length, or press ENTER to exit!");
Console.Write("Enter a string : ");
string str = Console.ReadLine();
// If the string is null, empty or only contains white spaces,
// break out of the loop.
if (string.IsNullOrWhiteSpace(str))
{
Console.Write("OK. You pressed Enter. See you agian!");
break;
}
Console.WriteLine(str.ToUpper());
Console.WriteLine("Numer of Chars is : " + str.Length);
};
I would try
if(Console.KeyAvailable)
{
cki = console.ReadKey();
...
}
You were close:
private void ShowStringLength()
{
ConsoleKeyInfo cki;
do
{
Console.WriteLine("Let me calculate the length of strings for you!");
Console.WriteLine("Give me text of any length, or press ENTER to exit!");
Console.Write("Enter a string : ");
String str = Console.ReadLine();
Console.WriteLine(str.ToUpper());
int len = str.Length;
Console.WriteLine("Numer of Chars is : " + len);
//Reads “Enter” from the keyboard to exit the app
cki = Console.ReadKey();
if (cki.Key == ConsoleKey.Enter)
{
Console.Write("OK. You pressed Enter. See you agian!");
}
else
{
Console.WriteLine(); //To start with a clean line
}
} while (cki.Key != ConsoleKey.Enter);
}
I wrote a code to made what you ant and i added a character ;in this sample space;
to determine that the string is finished. then calculated the length of string.
using System;
using System.Collections.Generic;
using System.Linq;
namespace ConsoleApp1
{
class Program
{
static void Main()
{
Console.WriteLine("Press <Enter> to exit... ");
var outPutString = "";
var list = new List<int>();
while (true)
{
Console.WriteLine("Let me calculate the length of strings for you!");
Console.WriteLine("Give me text of any length, or press ENTER to exit!");
Console.Write("Enter a string End with space : ");
var readKey = Console.ReadKey().Key;
if (readKey == ConsoleKey.Enter)
{
Console.WriteLine(
$"Length of {outPutString} is : {(string.IsNullOrWhiteSpace(outPutString) ? 0 : outPutString.Length)}");
break;
}
while (readKey != ConsoleKey.Spacebar)
{
if (readKey == ConsoleKey.Enter)
{
Console.WriteLine(
$"Length of {outPutString} is : {(string.IsNullOrWhiteSpace(outPutString) ? 0 : outPutString.Length)}");
break;
}
var result = ((int) readKey);
list.Add(result);
outPutString = list.Aggregate(outPutString, (current, item) => current + (char) item);
list.Clear();
readKey = Console.ReadKey().Key;
}
Console.WriteLine(
$"Length of {outPutString} is : {(string.IsNullOrWhiteSpace(outPutString) ? 0 : outPutString.Length)}");
outPutString = "";
}
}
}
}

How to loop a Console.ReadLine to the infinite?

Hello i'm trying to create a calculator game but it loops only 2 times and (idk why)not til the user finds the result with input. And i'll later see how to make a random generator of numbers instead of writing them by myself in the code. Ty for helping.
Yassine
using System;
namespace G
{
class Program
{
static void Main(string[] args)
{
Calcul(2, 2);
}
static void Calcul(int nombre1, int nombre2)
{
int result = nombre1 + nombre2;
Console.WriteLine("Combien font " + nombre1 + " + " + nombre2);
int supposed = int.Parse(Console.ReadLine());
if(result != supposed)
{
Console.WriteLine("Try again!");
supposed = int.Parse(Console.ReadLine());
}
else
{
Console.Clear();
Console.WriteLine("Correct!");
}
}
}
}
You can change your if statement to a while loop whose condition is that the input does not match the result. We can also use int.TryParse with Console.ReadLine to handle cases where the user doesn't enter a valid number. This works by taking an out parameter that gets set to the parsed value if it's successful, and it returns a bool that indicates success. Perfect for a loop condition!
Then you can put the "success" message after the body of the while loop (because the only way to exit the loop is to get the correct answer). It would look something like:
static void Calcul(int nombre1, int nombre2)
{
int result = nombre1 + nombre2;
int input;
Console.Write($"Combien font {nombre1} + {nombre2} = ");
while (!int.TryParse(Console.ReadLine(), out input) || input != result)
{
Console.WriteLine("Incorrect, please try again.");
Console.Write($"Combien font {nombre1} + {nombre2} = ");
}
Console.WriteLine("Correct! Press any key to exit.");
Console.ReadKey();
}

C# code issue - Code not working properly

I wrote a basic number guessing game from C#. It seems to return the 3rd option ("Wrong choice! Please try again.") every time no matter what var c is chosen by the user. I was trying with characters (s instead of 1 and w instead of 2 etc with c as a string) but it gave the same results. Not sure where it's going bad.
using System;
namespace Challanges
{
class Program
{
static int guess = 500;
static int low = 1;
static int high = 1000;
static bool cont = false;
static void Guess() //guesses and adjusts variables according to input.
{
int c;
Console.WriteLine("Is your number greater or less than: " + guess + Environment.NewLine + "If it is less than, press 1; if it is greater, press 2." + Environment.NewLine + "If it is your number, press 3.");
c = Convert.ToInt32(Console.Read());
if (c == 1)
{
high = 500;
guess = low + high / 2;
}
else if (c == 2)
{
low = 500;
guess = low + high / 2;
}
else if (c == 3)
{
Console.WriteLine("Congratulations!! We found your number!");
cont = true;
}
else
{
Console.WriteLine("Wrong choice! Please try again.");
Console.ReadKey();
}
}
static void Main(string[] args)
{
Console.WriteLine("Hello World!" + Environment.NewLine + "Let's play a guessing game. Think of a number between 1 and 1000." + Environment.NewLine + "Type your number :)");
int x = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("Your number is: " + x + Environment.NewLine + "Too easy?");
Console.ReadKey();
Console.WriteLine("Think of a number");
if(cont == false)
{
Guess();
} else
{
Console.ReadKey();
}
}
}
}
As mentioned in the comments before, Console.Read() returns a character code. The character code for the number 1 is 49, thus your conditions fail and the else block is executed.
What you wanted to do was use Console.ReadLine()which returns a string instead of character codes. If you cast that string into an Int32 you should be able to evaluate your conditions correctly.

How can I make a program loop back to the start if else is true? C#

Couldn't find any other answer on the site that covers this. If else is run and an error message is displayed, is it possible to restart the program by looping back to the start instead of restarting the console?
class Program
{
static void Main(string[] args)
{
int User;
int Array;
StreamWriter outfile = new StreamWriter("C://log.txt");
Console.WriteLine("Input an number between 1 and 100");
User = Convert.ToInt32(Console.ReadLine());
if (User < 101 && User > 0)
{
for (Array = 1; Array <= User; Array++)
{
Console.WriteLine(Array + ", " + Array * 10 * Array);
outfile.WriteLine(Array + ", " + Array * 10 * Array);
}
{
Console.WriteLine("Press Enter To Exit The Console");
outfile.Close();
Console.ReadLine();
}
}
else
{
Console.WriteLine("Sorry you input an invalid number. ");
Console.ReadLine();
}
}
}
Sorry! To be more clear I need to make the Program start again if the user inputs an invalid number
Thanks for the help!
You can do this instead
User = Convert.ToInt32(Console.ReadLine());
while (User >= 101 || User <= 0)
{
Console.WriteLine("Sorry you input an invalid number. ");
User = Convert.ToInt32(Console.ReadLine());
}
An easy way of doing this is placing your code inside a while loop, so that the code keeps repeating. The only way to exit the loop would be for the condition you just set in the if clause to be true. So something along the lines of:
class Program
{
static void Main(string[] args)
{
int User;
int Array;
bool isUserWrong = true; //This is a flag that we will use to control the flow of the loop
StreamWriter outfile = new StreamWriter("C://log.txt");
while(isUserWrong)
{
Console.WriteLine("Input an number between 1 and 100");
User = Convert.ToInt32(Console.ReadLine());
if (User < 101 && User > 0)
{
for (Array = 1; Array <= User; Array++)
{
Console.WriteLine(Array + ", " + Array * 10 * Array);
outfile.WriteLine(Array + ", " + Array * 10 * Array);
}
isUserWrong = false; // We signal that we may now leave the loop
}
else
{
Console.WriteLine("Sorry you input an invalid number. ");
Console.ReadLine();
//Note that here we keep the value of the flag 'true' so the loop continues
}
}
Console.WriteLine("Press Enter To Exit The Console");
outfile.Close();
Console.ReadLine();
}
}

Validation of input - Numbers vs. Letters

I am creating a short C# console program that will ask 10 addition questions using random numbers from 0-10. Then it tells the user how many correct or incorrect answers they had. I am trying to find a way to validate that my user input is a number and not a letter. I am posting the code I have created so far, but could use some help.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
int i = 0;
int input;
int correct = 0;
int incorrect = 0;
int questions = 10;
int[] solutions = new int[21];
int[] answers = new int[21];
int[] number1 = new int[21];
int[] number2 = new int[21];
Random number = new Random();
Console.WriteLine(" This is a test of your basic addition skills. ");
Console.WriteLine(" Please answer the random addition question below ");
Console.WriteLine(" with a number from 1 - 20 and press enter to get the");
Console.WriteLine(" next of 10 questions. At the end of the questions");
Console.WriteLine(" your results will be calculated and presented to you.");
Console.WriteLine("");
Console.WriteLine("");
while (i < questions)
{
number1[i] = number.Next(0, 10);
number2[i] = number.Next(0,10);
solutions[i] = (number1[i] + number2[i]);
//Console.WriteLine("{0} + {1} = {2}", number1[i], number2[i],solutions[i]);
Console.Write(" {0} + {1} = ", number1[i], number2[i]);
answers[i] = Convert.ToInt32(Console.ReadLine()); // original code
//input = Convert.ToInt32(Console.ReadLine());
//if (input > 0 && input <21)
//{
// Console.WriteLine("YOur answer is: {0}", input);
//}
//else
//Console.WriteLine("YOur answer is not valid");
if (solutions[i] == answers[i])
{
Console.WriteLine(" Correct");
correct++;
}
else
{
Console.WriteLine(" Your answer is incorrect, the correct answer is {0}", solutions[i]);
incorrect++;
}
//Console.WriteLine("{0}", answers[i]);
//int sum = numberone + numbertwo;
//answers[sum]++;
i++;
}
Console.WriteLine("");
Console.WriteLine("");
Console.WriteLine("The number correct is: {0}, The number incorrect is: {1}", correct, incorrect);
}
}
}
Use int.TryParse() like:
bool isNumber=false;
int number;
while (!isNumber)
{
string txt = Console.ReadLine();
if (!int.TryParse(txt, out number))
{
// not a number, handle it
Console.WriteLine("This is not a number, enter a number. For real now.");
}
else
{
// use number
answers[i] = number;
isNumber = true;
}
}
Instead of:
answers[i] = Convert.ToInt32(Console.ReadLine()); // original code
Use:
int input;
bool validInput = int.TryParse(Console.ReadLine(), out input);
if (!validInput || input < 0 && input > 20)
<throw exception or display some error message here...>
EDIT: If you want to recursively ask for a correct input, this is how you can do it:
int input;
bool validInput = false;
while (!validInput)
{
validInput = int.TryParse(Console.ReadLine(), out input);
if (!validInput || input < 0 && input > 20)
{
validInput = false; // We need to set this again to false if the input is not between 0 & 20!
Console.WriteLine("Please enter a number between 0 and 20");
}
}
int iResult = int.MinValue;
bool bParsed = int.TryParse("xyz", out iResult);
TryParse will not throw an exception.
However, you can use Convert.ToInt32() as well if needed but that will throw an exception on bad data.
Something like:
if (int.TryParse(Console.ReadLine(), out answers[i]) && answers[i] > 0 && ...)
{
...
}
else
{
// invalid answer
}
This allows you to fill all positions of your array:
int result;
bool isInt = Int32.TryParse(Console.ReadLine(), out result);
if (!isInt) {
Console.WriteLine("Your input is not an integer number.");
continue;
}
answers[i] = result;

Categories

Resources