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
Related
The following code below is concatenating the double variable .
For example first number is 2
And second is 3
It is adding them like this 2+3;
23
using System;
public static class Program
{
public static void Main()
{
double num01;
double num02;
Console.WriteLine("Add");
Console.Write("type a number: ");
num01 = Convert.ToInt32(Console.ReadLine());
Console.Write("type another number: ");
num02 = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("the result is " + num01 + num02);
Console.ReadKey();
}
}
You have not added 2 integers together, you have suffixed a string with 2 other numbers.
String concatenation is also 'slow'. You should use string.Format or string interpolation.
Console.WriteLine(string.Format("the result is {0}", num01 + num02) );
or
Console.WriteLine($"the result is {num01 + num02}");
The reson is that expression "the result is " + num01 + num02 is adding, which includes string, which makes the whole operation concatentaion, not addition of numbers! If at least one operand of + operator is string, it makes it concatenation.
Moreover, then every other operand is converted to string, so your numbers get converted to string and then concatenated.
To prevent that, force order of operation, so addition of your numbers is first, for example (already shown in other answers): "the result is " + (num01 + num02)
Now it will first sum two numbers, then concatenate with given string.
If you add the parentheses to the sum of the number, your code can work
double num01;
double num02;
Console.WriteLine("Add");
Console.Write("type a number: ");
num01 = Convert.ToInt32(Console.ReadLine());
Console.Write("type another number: ");
num02 = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("the result is " + (num01 + num02));
Console.ReadKey();
but the best practice without a doubt is:
string.Format
"It is adding them like this 2+3; 23 "
That is because you are using + in a context where it treats 2 and 3 as strings and with strings + always perform concatenation, hence the result 23
What do you need to do to fix things?
Console.WriteLine("the result is " + (num01 + num02) );
Why does the above solution works?
Short answer: Operator precedence. Parenthesis has higher precedence and is evaluated first. When that happens num01 and num02 are treated as numbers and addition takes place. And now this sum value is treated like a string in + with "the result is "
What's going on: for
"the result is " + num01 + num02
we have
"the result is " + num01 which is "the result is 1" (adding double to string)
"the result is 1" + num02 which is "the result is 12" (adding double to string)
what can you do: put (..) and have "the result is " + (num01 + num02):
num01 + num0 which is 3 (adding two doubles)
"the result is " + 3 which is "the result is 3" (adding double to string)
So you can either put (...)
Console.WriteLine("the result is " + (num01 + num02));
or (better way) use string interpolation and let .net compute the sum for you:
Console.WriteLine($"the result is {num01 + num02}");
or formatting:
Console.WriteLine("the result is {0}", num01 + num02);
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
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);
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 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