Console.Read() doesn't allow me to input anything the second time - c#

I'm solving a problem about comparing two floating-point numbers and I want to let the user input desired values. So I wrote the following code:
Console.WriteLine("Enter first number: ");
double num1 = Console.Read();
Console.WriteLine("Enter second number: ");
double num2 = Console.Read();
Unfortunately, I can only input the first number. After the console outputs "Enter first number: " and I enter some number, it simply skips to the end and doesn't let me enter the second number... Any thoughts on that?

That is the default behaviour of Console.Read(). From an answer on Difference between Console.Read() and Console.ReadLine()?
Console.Read() basically reads a character so if you are on a console and you press a key then the console will close. [...]
You should use Console.ReadLine(); instead.
Console.WriteLine("Enter first number: ");
double num1 = double.Parse(Console.ReadLine());
Console.WriteLine("Enter second number: ");
double num2 = double.Parse(Console.ReadLine());

It assumes that you enter already \n as a second input. If you enter 2 numbers on the first Read method. Than it tooks 1 number in first read and second number on the second automatically. Just replace with ReadLine() if you want to achieve noraml behaviour,

Try Console.ReadLine() instead. Console.Read only reads a single character
Console.WriteLine("Enter first number: ");
double num1 = double.Parse(Console.ReadLine());
Console.WriteLine("Enter second number: ");
double num2 = double.Parse(Console.ReadLine());
Or with TryParse:
Console.WriteLine("Enter first number: ");
double num1, num2;
double.TryParse(Console.ReadLine(), out num1); // double.TryParse() method also returns a bool, so you could flag an error to the user here
Console.WriteLine("Enter second number: ");
double.TryParse(Console.ReadLine(), out num2);

Related

user input validation of int length

l am writing a class assignment for a simple login program where user will input username, password and mobile number on the console. My problem is on the mobile number, l want them to input a 10 digit number and only 10, if they input less or more than 10 it must show an error. Here is my code so far:
Console.WriteLine("Please enter your Mobile Number:");
Console.WriteLine("**Please note Mobile Number should be 10 digits only e.g 07...");
//AVOIDS EXCEPTION HANDLING OF ENTERING ANY TYPE THAT IS NOT AN INTEGER
while (!int.TryParse(Console.ReadLine(), out Option)) {
Console.WriteLine("***************************************************");
Console.WriteLine("Please Enter a valid numerical value!");
Console.WriteLine("Please Enter option 1 or option 2:");
}
Read the console in string variable, count the length and check if the string is a digit.
//code
string mobNo = Console.ReadLine();
if(mobNo.Length == 10)
{
bool isNum = int.TryParse(mobNo);
if(isNum)
//continue code
}
//return error

Displaying the input before it's converted

I am making a temperature conversion program and I cant figure out how to do the last part. The program allows the user to pick choose either a Fahrenheit to Celsius or Celsius to Fahrenheit converter.
This is my code so far.
case "1":
System.Console.Write("Please enter the Celsius temperature: ");
F = TemperatureConverter.CelsiusToFahrenheit(System.Console.ReadLine());
System.Console.WriteLine("Celsius is {0:F2} Fahrenheit", F);
break;
Right now if the user enters 1 into the Celsius to Fahrenheit converter then it will output will be
"Celsius is 33.80 Fahrenheit"
I want the output to display
"1 Celius is 33.80 Fahrenheit"
I just can't figure out how to display what the user entered in the same line before F is converted.
You need to store the result of the input to a variable:
string input = Console.ReadLine();
You would then use that:
F = TemperatureConverter.CelsiusToFahrenheit(input);
System.Console.WriteLine("{0} Celsius is {1:F2} Fahrenheit", input, F);
Side note that you should be validating the user input, and use a TryParse method as that won't throw an exception like Parse will. I am also assuming the user input should be an int, use the relevant validation for your use case.
int parsedInput;
if (!Int32.TryParse(input, out parsedInput))
{
//Handle invalid input here.
}
Note that in C# 7.0 you should be able to do the following that is cleaner.
if (!Int32.TryParse(input, out int parsedInput))
Note: You should also validate your Input (check if it's numeric).
int enteredValue;
if(int.TryParse(System.Console.ReadLine(), out enteredValue);
{
//Check if enteredValue has been set to your needs !
//Store your converted Value
double convertedValue = TemperatureConverter.CelsiusToFahrenheit(enteredValue); // I assume double here ..
//Display the result on your console:
System.Console.WriteLine($"{enteredValue} Celsius is {convertedValue} Fahrenheit");
}
else { /*Handle wrong input here*/ }
I am using string interpolation !
case "1":
System.Console.Write("Please enter the Celsius temperature: ");
String userInput = System.Console.ReadLine();
System.Console.Write(userInput);
F = TemperatureConverter.CelsiusToFahrenheit(userInput);
System.Console.WriteLine(" Celsius is {0:F2} Fahrenheit", F);
break;
All you need to do is store the user input in a variable and then access that in your write line statement.
case "1":
System.Console.Write("Please enter the Celsius temperature: ");
var userInput = System.Console.ReadLine();
F = TemperatureConverter.CelsiusToFahrenheit(userInput);
System.Console.WriteLine($"{userInput} Celsius is {0:F2} Fahrenheit", F);
break;
Or instead of using an extra var and you don't need F to be on Fahrenheit later on you could do:
case "1":
System.Console.Write("Please enter the Celsius temperature: ");
F = System.Console.ReadLine();
System.Console.WriteLine("{0} Celsius is {1:F2} Fahrenheit", F, TemperatureConverter.CelsiusToFahrenheit(F));
break;

Console.Writeline -- Why output is missing

Absolute newbie to C#. Was trying to run this program and the output simply would not show any computations.Why? I did not want to go through p,q,r,s for add, sub, multiply, divide etc., Also, how can i put space between "Please enter a number" and userName?
string userName;
double x, y;
Console.WriteLine(" Enter Your Name ");
userName = Console.ReadLine();
Console.WriteLine(" Please Enter A Number "+ userName);
First = Convert.ToDouble(Console.ReadLine());
Console.WriteLine("Please Enter Another Number"+ userName);
Second = Convert.ToDouble(Console.ReadLine());
Console.WriteLine("The addition of Two Numbers is",x,y, x*y);
Console.WriteLine("The substraction of Two Numbers is",x,y,x/y);
Console.WriteLine("The multiplication of Two Numbers is",x,y,x * y);
Console.WriteLine("The division of Two Numbers given is", x,y,x / y);
Console.ReadKey();
When you pass additional parameters to show output, you must tell WriteLine where to put it by adding placeholders to the format line, like this:
Console.WriteLine("The product of Two Numbers {0} and {1} is {2}", x, y, x*y);
Positions are zero-based. The printed value of the first additional parameter (i.e. x) will replace {0}; the value of y will replace {1}, and the value of x*y will replace {2} in the final output.
The reason you did not have to do it with userName is that you passed a single parameter:
Console.WriteLine("Please Enter Another Number " + userName);
The result of appending userName to "Please Enter Another Number" string is passed as a single parameter to WriteLine. You could rewrite it with a format specifier, like this:
Console.WriteLine("Please Enter Another Number {0}", userName);
Totally agree with dasblinkenlight. Additionally, you may meet this line of code
Console.WriteLine("{0}, {1}", "Hello", 53);
Result in this line being written: Hello, 53. {0} is the placeholder for the first argument after the format string, {1} is the second, and so on. This is called composite formatting in .NET - http://msdn.microsoft.com/en-us/library/txafckwd%28v=vs.110%29.aspx

What am I doing wrong? /noob ?Learning to program

I am trying to create a simple calculator in the console for single digit numbers.(Well I actually only care about multiplication)
So, here is my code and if someone could help me.
class multiplythisnumber
{
static void Main()
{
int input, input1, output; //variable decleration
System.Console.WriteLine("This application is meant to multiply two single digit numbers.");
System.Console.WriteLine("You can choose both numbers, however this is only a test.\r I am not sure the read command even does what I think it does.");
System.Console.WriteLine();
System.Console.Write("Please enter the first number: ");
input = System.Console.Read(); //Reads my input + 48(assuming 48 is the value of enter)
input = input - 48;
System.Console.WriteLine();
System.Console.Write("Please enter the second number: ");
input1 = System.Console.Read(); //Doesn't wasit for input and sets input1 = 13
System.Console.WriteLine();
output = input * input1;
System.Console.WriteLine();
System.Console.Write("{0} times {1} equals {2}.", input, input1, output);
System.Console.ReadKey();
}
}
I added comments to explain what I was doing to everyone else, and just as personal notes.
The last line always ends up as "(0) times 13 equals 0." -Assuming I used zero for input 1.
Edit:
Just to clarify I know 0*13=0 (yes it said 12 earlier what it has really been saying is 13). The problem is that it is not allowing me to set input1 and is just setting it at 13 and continuing executing.
Edit2: I would like to say thanks to Matt, because the changes he made allowed the code to work correctly. So, looks like I have my first code that actually does something other than tell you your own name.
Console.Read() only reads one character. So your first Console.Read() reads your number and the second reads the CR Ascii code (13) because of your "Enter".
Use ReadLine() instead.
System.Console.Write("Please enter the first number: ");
string first = System.Console.ReadLine();
input = Convert.ToInt32(first);
System.Console.WriteLine();
System.Console.Write("Please enter the second number: ");
string second = System.Console.ReadLine();
input1 = Convert.ToInt32(second);
System.Console.WriteLine();
output = input * input1;
System.Console.WriteLine();
System.Console.Write("{0} times {1} equals {2}.", input, input1, output);
System.Console.ReadKey();
The problem is that you are reading two characters one after the other. input is set when you press the 1 key. input1 is read when you press the Enter key. Just don't press the Enter key; instead enter both numbers immediately one after the other. The best way to solve this is System.Console.ReadLine
System.Console.Read reads a single character from the console. When you type the 0 key, your program actually reads the character '0' ('0' == 48 in ASCII) not the number 0.
Here's how I would fix your program:
Instead of using System.Console.Read, which reads a character, I would use System.Console.ReadLine which reads an entire line rather than a single key/character. This would allow your users to enter numbers longer than one digit. You can convert the user's input from a string to an integer by using Int32.Parse
class multiplythisnumber
{
static void Main()
{
int input, input1, output; //variable decleration
System.Console.WriteLine("This application is meant to multiply two single digit numbers.");
System.Console.WriteLine("You can choose both numbers, however this is only a test.\r I am not sure the read command even does what I think it does.");
System.Console.WriteLine();
System.Console.Write("Please enter the first number: ");
input = Int32.Parse(System.Console.Read());
//input = input - 48;//No need to do this anymore as we have already converted the user's input to an integer.
System.Console.WriteLine();
System.Console.Write("Please enter the second number: ");
input1 = Int32.Parse(System.Console.ReadLine());
System.Console.WriteLine();
output = input * input1;
System.Console.WriteLine();
System.Console.Write("{0} times {1} equals {2}.", input, input1, output);
System.Console.ReadKey();
}
}
It has to do with how Read() and ReadLine() work. Try ReadLine() instead.
I believe it is because your program is using Console.Read() instead of Console.ReadLine() This means that it is reading 1 character at a time from the input. Your first input is 5 + a return. Try using ReadLine and you need to protect against entering something that isn't an integer. You can use the following program to achieve what you want.
class Program
{
static void Main(string[] args)
{
int input, input1;
string output; //variable decleration
System.Console.WriteLine("This application is meant to multiply two single digit numbers.");
System.Console.WriteLine("You can choose both numbers, however this is only a test.\r I am not sure the read command even does what I think it does.");
System.Console.WriteLine();
System.Console.Write("Please enter the first number: ");
int.TryParse(System.Console.ReadLine(),out input); //Reads my input
System.Console.WriteLine();
System.Console.Write("Please enter the second number: ");
int.TryParse(System.Console.ReadLine(), out input1);
System.Console.WriteLine();
if (input != 0 && input1 != 0) {
input = input - 48;
output = (input * input1).ToString();
}else
{
output = "NaN";//not a number
}
System.Console.WriteLine();
System.Console.Write("{0} times {1} equals {2}.", input, input1, output);
System.Console.ReadKey();
}
}
May be you need an C# expert to answer, but when I debug I got that, because when you ENTER, it will push to Console 13 and 10. So you need to Read twice to through them.
Just COPY and PASTE to your code
static void Main()
{
int input, input1, output; //variable decleration
System.Console.WriteLine("This application is meant to multiply two single digit numbers.");
System.Console.WriteLine("You can choose both numbers, however this is only a test.\r I am not sure the read command even does what I think it does.");
System.Console.WriteLine();
System.Console.Write("Please enter the first number: ");
input = System.Console.Read(); //Reads my input + 48(assuming 48 is the value of enter)
input = input - 48;
/**
*HINT: Try to use below double line:
*/
System.Console.Read();
System.Console.Read();
System.Console.Write("Please enter the second number: ");
input1 = System.Console.Read(); //Doesn't wasit for input and sets input1 = 13
System.Console.Read();
output = input * input1;
System.Console.WriteLine();
System.Console.Write("{0} times {1} equals {2}.", input, input1, output);
System.Console.ReadKey();
}
UPDATE:
You can try to see more:
static void Main()
{
Console.Write("Please enter just one number and press enter:");
int input1 = Console.Read();
int input2 = Console.Read();
int input3 = Console.Read();
Console.WriteLine("You've inputted: {0},{1},{2}",input1, input2, input3);
Console.ReadKey();
}
Output:
Please enter just one number and press enter:1
You've inputted: 49,13,10

I want to print the value in sales

I want to print the value of the amount of sales entered by user times .10. My first issue is I want to store a value that a user enters into sales then times that by .10 then print the value of sales. We I run the program I get two lines one is the amount of sales entered the other is .5.
const double COMMRATE = 0.10;
string inputstring;
double sales =5;
char response;
Console.Write("Do you want to Calculate Sales A or B or E...");
inputstring = Console.ReadLine();
response = Convert.ToChar(inputstring);
while (response == 'A')
{
Console.WriteLine("Enter Sales", sales.ToString("C"));
sales = sales * COMMRATE;
inputstring = Console.ReadLine();
response = Convert.ToChar(inputstring);
}
Your .5 is coming about because you've set the default value of sales to be 5, and 5 * 0.1 = 0.5.
But why is that happening? Let's take apart your loop:
It asks the user to enter an amount of sales. The second parameter is ignored, because "Enter Sales" has no format string placeholders. It does not perform line-reading of any form.
Without asking for input, it multiplies Sales by the commission rate and stores that to Sales.
Now it asks for user input,
which it immediately spits back out exactly as written (the amount-of-sales-entered line.)
What you actually need to be doing is a second Console.ReadLine() to get a string for the amount of sales, then use Double.ParseDouble() to get the entered amount of sales. Multiply that by your COMMRATE and print that back out- then give your "Do you want to Calculate..." question again, and then use the response from that to decide whether or not to continue the loop- currently, response is never getting modified, so you've created an infinite loop.
Unfortunately, you aren't even really close to the right code here. Your loop should look more like
while (response == 'A'){
Console.WriteLine("Enter Sales");
string salesStr = Console.ReadLine();
Console.WriteLine(Double.Parse(salesStr) * COMMRATE);
Console.WriteLine("Enter A to continue, anything else to quit");
response = Convert.ToChar(Console.ReadLine());
}
...which should get you started towards making your program do what you want.
Is this what you intend?
const double COMMRATE = 0.10;
string inputstring;
double sales;
char response;
Console.Write("Do you want to Calculate Sales A or B or E...");
inputstring = Console.ReadLine();
response = Convert.ToChar(inputstring);
while (response == 'A')
{
Console.WriteLine("Enter Sales");
inputstring = Console.ReadLine();
sales = Double.Parse(inputstring);
Console.WriteLine("Sales = " & sales);
Console.WriteLine("Commission = " & sales * COMMRATE);
}
I'm having a hard time discerning what exactly you're asking.
If you want to print the value multiplied by the COMMRATE then you should probably put the calculation above the write statement.
sales = sales * COMMRATE;
Console.WriteLine("Enter Sales", sales.ToString("C"));
Although since you said you want to STORE the value entered by the user and THEN print it times the COMMRATE maybe you should use something like
double calculatedSales = sales * COMMRATE
Console.WriteLine("Enter Sales", calculatedSales.ToString("C"));
so that you're not redefining the original sales amount

Categories

Resources