readline stops code

Aphyro

Member
Joined
Oct 16, 2017
Messages
5
Programming Experience
Beginner
{
Console.Write("Enter Temperature: 89");
string str = Console.ReadLine();
int temperature = Convert.ToInt32(str);
if (temperature == 100)
{
Console.WriteLine("Now the water boils!");
}
else
{ Console.WriteLine("The water is not exactly 100 degrees...");

}

It is suposed to show Enter Temperature: 89
The water is not exactly 100 degrees

But it only shows Enter temperature: 89 for me and if i press enter the consol just shuts down...
 
It is suposed to show Enter Temperature: 89
The water is not exactly 100 degrees

But it only shows Enter temperature: 89 for me and if i press enter the consol just shuts down...
Take a step back and think about what you're doing with your code.

You're writing "Enter Temperature: 89" to the console, then having it collect input from the user (.ReadLine()) right after which is being stored in the variable. When you press Enter without having typed anything in, what do you think the value of str is going to be?
If you guessed "" (an empty string) then you guessed right, so what do you think an empty string is going to convert to? My guess would be a 0 which brings us to the If statement where the 0 would cause it to write "he water is not exactly 100 degrees..." to the console but then there's no "Read()" or "ReadLine()" call to keep the program (and the console window) open so it closes rather quickly, which I believe is the issue you're having, but I wanted to highlight the other issue with the code too.

Using the debugging tools, like stepping through code, will help with identifying these kinds of things.
 
You have to enter a temperature and then press return. Readline is expecting some key data other than a return key.

100 <enter>
 

Latest posts

Back
Top Bottom