Good day all, I'm new to C# and currently at the stage of experimenting with if-else statements. Upon declaring variables ageUser, permittedAge, input and running the program, I noticed that the if statement and the resulting output don't seem to match.
int ageUser;
int permittedAge = 18;
int input;
Console.Write("Put in your age: ");
input = Convert.ToInt32(Console.Read());
ageUser = input;
if (ageUser < permittedAge)
{
Console.WriteLine("Sorry you are not permitted to enter this site!");
}
else
{
Console.WriteLine("Welcome");
}
Link To Console Output
You will need to change how you read in the input. Read() reads in a character and does not convert that to int like you think it does. (5 becomes 53 due to its ASCII representation). Use ReadLine instead.
Use the folowing instead.
Console.Write("Put in your age: ");
input = Convert.ToInt32(Console.ReadLine());
ageUser = input;
Related
Quick question how do I use same variable for string input in case and int input in another case. Here is what I mean by that, I have a problem where I need to constantly insert number and then put the addition of those numbers inside another variable. This inserting is inside do while loop, for me to exit the loop and to show the sum of those numbers, I need to type "OK" or "ok". I have a problem where I do not know how to use string variable for int inputs.
Here is my code:
string input= "";
int sum = 0;
do
{
Console.WriteLine("Insert the number or OK (ok) for exit: ");
input = Console.ReadLine();
sum += Convert.ToInt32(input);
// this is where I get the error Input string was not in the correct fromat
} while (input != "OK" && input != "ok");
Console.WriteLine(sum)
If anyone knows how to help me with this, I would gladly appreciate it.
First identify that the user entered integer or not using int.TryParse(), if user entered integer then add it to the sum variable otherwise check the string
do
{
Console.WriteLine("Insert the number or OK (ok) for exit: ");
input = Console.ReadLine();
//This will add number only if user enters integer.
if(int.TryParse(input, out int number)
sum += number
} while (input != "OK" && input != "ok");
You have to test for OK before you try to convert to a number, because OK won't convert to a number
string input= "";
int sum = 0;
while(true)
{
Console.WriteLine("Insert the number or OK (ok) for exit: ");
input = Console.ReadLine();
if("OK".Equals(input, StringComparison.OrdinalIgnoreCase)) //do a case insensitive check. Note that it's acceptable to call methods on constants, and doing a string check this way round cannot throw a NullReferenceException
break;//exit the loop
sum += Convert.ToInt32(input);
}
Console.WriteLine(sum);
You'll still get the error if the user enters input other than OK, that is not convertible to a number, but this is the crux of your current problem. I'll leave dealing with other garbages as an exercise for you...
Sorry if this isn't the right. This is my first time posting here. I'm a first year Software student and for the life of me i cannot seem to get this to work. I know its something simple I'm missing but oh well. I tried doing this using methods but again no help. Maybe you guys could help me?
The problem is the code wont let me input after the "Are you a member (Y/N)" writline statement and just keeps giving me an output of 50.
static void Main(string[] args)
{
//Local Variable Declaration//
double rate1 = 10;
double rate2 = 3;
double maxCharge = 50;
double charge;
Console.WriteLine("Enter number of hours (-999 to quit) : ");
int hoursRented = Console.Read();
if (hoursRented >= 3)
{
charge = hoursRented * rate1;
}
else
{
charge = (3 * rate1) + (hoursRented * rate2);
}
if (charge > maxCharge)
{
charge = maxCharge;
}
Console.WriteLine("Are you a member? (Y/N) : ");
int memberStatus = Console.Read();
if (memberStatus.Equals("Y"))
{
charge = (charge * 1 / 10) - charge;
}
Console.WriteLine("Customer Charge : {0} Total Charge To Date : ", charge);
}
The problematic lines are below
Console.WriteLine("Enter number of hours (-999 to quit) : ");
int hoursRented = Console.Read();
if (hoursRented >= 3) {
and
Console.WriteLine("Are you a member? (Y/N) : ");
int memberStatus = Console.Read();
if (memberStatus.Equals("Y")) {
When you call Console.Read(), it reads only characters and returns it as an int. You seem to mistakenly think it will parse the character to an int.
Secondly, think what happens when you provide multiple characters as input to a single Console.Read() call. Interestingly, the remaining characters are read in the subsequent calls. So when you type any number followed by Enter in the first Console.Read it only, reads the first character, the subsequent characters, including the EOLN char are returned in the subsequent calls, instead of prompting you to enter information for the next call.
The fix is easy. Use Console.Readline() and int.parse (or its int.TryParse() variant
Then the corresponding code will look like below
Console.Write("Enter number of hours (-999 to quit) : ");
string hoursRentedStr = Console.ReadLine();
int hoursRented = int.Parse(hoursRentedStr);
if (hoursRented >= 3) {
and
Console.Write("Are you a member? (Y/N) : ");
string memberStatus = Console.ReadLine();
if (memberStatus.Equals("Y")) {
This is because you are just writing:
Console.WriteLine("Are you a member? (Y/N) : ");
and continuing through.
you must do it like this:
Console.WriteLine("Are you a member? (Y/N) : ");
Console.ReadLine();
and then:
int memberStatus = Int.Parse(Console.ReadKey());
your problem is that your are using Console.Read wich returns the ascii code of the next charachter as said by #juharr in the comments. so the solution is too simply replace Read By ReadLine and change your code like this, so that ReadLine wich is a string will be converted to the int value that you want
int hoursRented = int.Parse(Console.ReadLine());
And change your member status to a string to compare it with "Y" easily
string memberStatus = Console.ReadLine();
Note: if you want to validate the input you should use a int.TryParse instead of just a normal parse like I used as it returns a bool so you knows when it fails
This question already has answers here:
Console.Read not returning my int32 [duplicate]
(7 answers)
Closed 1 year ago.
I have been trying to use Console.Read() and Console.ReadLine() in C# but have been getting weird results. for example this code
Console.WriteLine("How many students would you like to enter?");
int amount = Console.Read();
Console.WriteLine("{0} {1}", "amount equals", amount);
for (int i=0; i < amount; i++)
{
Console.WriteLine("Input the name of a student");
String StudentName = Console.ReadLine();
Console.WriteLine("the Students name is " + StudentName);
}
has been giving me that amount = 49 when I input 1 for the number of students, and Im not even getting a chance to input a student name.
This because you read a char.
Use appropriate methods like ReadInt32() that takes care of a correct conversion from the read symbol to the type you wish.
The reason why you get 49 is because it's a char code of the '1' symbol, and not it's integer representation.
char code
0 : 48
1 : 49
2: 50
...
9: 57
for example: ReadInt32() can look like this:
public static int ReadInt32(string value){
int val = -1;
if(!int.TryParse(value, out val))
return -1;
return val;
}
and use this like:
int val = ReadInt32(Console.ReadLine());
It Would be really nice to have a possibility to create an extension method, but unfortunately it's not possible to create extension method on static type and Console is a static type.
Try to change your code in this way
int amount;
while(true)
{
Console.WriteLine("How many students would you like to enter?");
string number = Console.ReadLine();
if(Int32.TryParse(number, out amount))
break;
}
Console.WriteLine("{0} {1}", "amount equals", amount);
for (int i=0; i < amount; i++)
{
Console.WriteLine("Input the name of a student");
String StudentName = Console.ReadLine();
Console.WriteLine("the Students name is " + StudentName);
}
Instead to use Read use ReadLine and then check if the user input is really an integer number using Int32.TryParse. If the user doesn't input a valid number repeat the question.
Using Console.Read will limit your input to a single char that need to be converted and checked to be a valid number.
Of course this is a brutal example without any error checking or any kind of safe abort from the loops.
For someone who might still need this:
static void Main(string[] args)
{
Console.WriteLine("How many students would you like to enter?");
var amount = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("{0} {1}", "amount equals", amount);
for (int i = 0; i < amt; i++)
{
Console.WriteLine("Input the name of a student");
String StudentName = Console.ReadLine();
Console.WriteLine("the Students name is " + StudentName);
}
}
you get a character char from read not an int. you will need to make it a string first and parse that as a string. THe implementation could look like the below
Console.WriteLine("How many students would you like to enter?");
var read = Console.ReadLine();
int amount;
if(int.TryParse(read,out amount)) {
Console.WriteLine("{0} {1}", "amount equals", amount);
for (int i=0; i < amount; i++)
{
Console.WriteLine("Input the name of a student");
String StudentName = Console.ReadLine();
Console.WriteLine("the Students name is " + StudentName);
}
}
I've changed it to use readline because readline returns a string an doesn't arbitrarily limits the number of students to 9 (the max number with one digit)
Console.Read() is returning the char code of the character that you enter. You need to use Convert.ToChar(amount); to get the character as a string, and then you will need to do int.Parse() to get the value you're looking for.
Console.Read returns the asci value of the key character that was pressed.
If you use Console.ReadKey().KeyChar you'll get a char that represents the actual character that was pressed.
You can then turn that character to a one character string by using .ToString().
Now that you have a string you can use int.Parse or int.TryParse to turn a string containing entirely numeric characters into an integer.
So putting it all together:
int value;
if (int.TryParse(Console.ReadKey().KeyChar.ToString(), out value))
{
//use `value` here
}
else
{
//they entered a non-numeric key
}
Instead of:
int amount = Console.Read();
try:
int amount = 0;
int.TryParse(Console.ReadLine(), out amount);
Its because You read just character code, so for example typing 11 You will still get 49. You need to read string value and the parse it to int value. With code above in case of bad input You will get 0.
Try this:
int amount = ReadInt32();
or if it doesn't work try this:
int amount = Console.ReadInt32();
or this:
int amount = Convert.ToInt32(Console.Readline());
In this, it will read string then it will convert it into Int32 value.
You can also go here: http://www.java2s.com/Tutorials/CSharp/System.IO/BinaryReader/C_BinaryReader_ReadInt32.htm
If nothing works, please let me know.
Console.WriteLine("How many students would you like to enter?");
string amount = Console.ReadLine();
int amt = Convert.ToInt32(amount);
Console.WriteLine("{0} {1}", "amount equals", amount);
for (int i = 0; i < amt; i++)
{
Console.WriteLine("Input the name of a student");
String StudentName = Console.ReadLine();
Console.WriteLine("the Students name is " + StudentName);
}
//thats it
TL;DR; Enter key in Windows isn't a single character. This fact is at the root of many issues related to Console.Read() method.
Complete Details:
If you run below piece of code on your computer then you can solve lot of mysteries behind Console.Read():
static void Main(string[] args)
{
var c = Console.Read();
Console.WriteLine(c);
c = Console.Read();
Console.WriteLine(c);
}
While running the program, hit the Enter key just once on your keyboard and check the output on console. Below is how it looks:
Interestingly you pressed Enter key just once but it was able to cater to two Read() calls in my code snippet. Enter key in windows emits two characters for a new line character namely carriage return (\r - ASCII code 13) and line feed (\n - ASCII code 10). You can read about it more here in this post - Does Windows carriage return \r\n consist of two characters or one character?
I'm trying to write a program in C# that takes in an int x and decides if it has exactly 7 digits. Right now I'm using x.toString().Length == 7 to check, but I noticed that if the number starts with 0, it automatically gets omitted and I get an incorrect answer (ie the program thinks the input length is less than 7)
Is there a way to fix this? Thanks in advance.
Edit: Sorry I should have mentioned, this was a program to collect and validate the format of ID numbers (so I didn't want something like 0000001 to default to 1) Thanks for the string input suggestion, I think I'm going to try that.
If you want to preserve the input formatting, you must not convert the input to an int. You must store it in a String.
You say your program takes an int. At that point you have already lost. You need to change that interface to accept String inputs.
If you don't care about leading zeros, you're really looking for 7 digits or less. You can check for:
x.toString().Length <= 7
or better:
x < 10000000
Maybe I'm wrong, but to me, 0000001 == 1, and 1 has one digit, not seven. So that's mathematically correct behaviour.
I think you could format it as a string:
int myInt=1;
myInt.ToString("0000000");
prints:
0000001.
so you could do:
if (myInt.ToString("0000000").Length==7)
You can simply write:
int input = 5;
if(input.ToString("0000000").Length == 7)
{
//do your stuff
}
No. It is perfectly valid for a numeric literal to have leading 0s, but a) many languages consider this to be an octal literal, and b) the leading 0s don't actually exist as part of the number. If you need a string then start with a string literal.
You should use string to check length count including 0.
Then I would like to ask "Why do you want to show 0000007? For What?"
You said you're asking for a int, but I suppose you're receiving it as string:
int i = 0;
string number = Console.ReadLine();
if (Int32.TryParse(number, out i))
{
//if (i.ToString().Length == 7) // you can try this too
if (i > 999999 && i < 10000000)
{
Console.WriteLine("Have exactly 7 digits");
}
else
{
Console.WriteLine("Doesn't have exactly 7 digits");
}
}
else
{
Console.WriteLine("Not an Int32 number");
}
This way you try to cast that received number as Int32 and, so, compare its length.
You can let the number be saved as an int with the omitted zeros. but then if you want the number displayed with the zeros then you can use an if statement and a while loop. for example,
Let's assume the values are stored in a numbers array and you need them to be stored as int so you can sort them but displayed as string so you can display with the leading zeros.
int[] numbers = new int[3];
numbers[0] = 001;
numbers[1] = 002;
numbers[2] = 123;
String displayed_Number;
for (int i = 0; i < numbers.Length; i++)
{
displayed_Number = numbers[i].ToString();
if (displayed_Number.Length == 3)
{
listBox.Items.Add(displayed_Number);
}
else if (displayed_Number.Length < 3)
{
while (displayed_Number.Length < 3)
{
displayed_Number = "0" + displayed_Number;
}
listBox.Items.Add(displayed_Number);
}
}
The output is 001 002 123
That way you can maintain the zeros in the numbers when displayed. and they can be stored as int in case you have to store them as int.
What would be the best way to fill an array from user input?
Would a solution be showing a prompt message and then get the values from from the user?
string []answer = new string[10];
for(int i = 0;i<answer.length;i++)
{
answer[i]= Console.ReadLine();
}
Could you clarify the question a bit? Are you trying to get a fixed number of answers from the user? What data type do you expect -- text, integers, floating-point decimal numbers? That makes a big difference.
If you wanted, for instance, an array of integers, you could ask the user to enter them separated by spaces or commas, then use
string foo = Console.ReadLine();
string[] tokens = foo.Split(",");
List<int> nums = new List<int>();
int oneNum;
foreach(string s in tokens)
{
if(Int32.TryParse(s, out oneNum))
nums.Add(oneNum);
}
Of course, you don't necessarily have to go the extra step of converting to ints, but I thought it might help to show how you would.
It made a lot more sense to add this as an answer to arin's code than to keep doing it in comments...
1) Consider using decimal instead of double. It's more likely to give the answer the user expects. See http://pobox.com/~skeet/csharp/floatingpoint.html and http://pobox.com/~skeet/csharp/decimal.html for reasons why. Basically decimal works a lot closer to how humans think about numbers than double does. Double works more like how computers "naturally" think about numbers, which is why it's faster - but that's not relevant here.
2) For user input, it's usually worth using a method which doesn't throw an exception on bad input - e.g. decimal.TryParse and int.TryParse. These return a Boolean value to say whether or not the parse succeeded, and use an out parameter to give the result. If you haven't started learning about out parameters yet, it might be worth ignoring this point for the moment.
3) It's only a little point, but I think it's wise to have braces round all "for"/"if" (etc) bodies, so I'd change this:
for (int counter = 0; counter < 6; counter++)
Console.WriteLine("{0,5}{1,8}", counter, array[counter]);
to this:
for (int counter = 0; counter < 6; counter++)
{
Console.WriteLine("{0,5}{1,8}", counter, array[counter]);
}
It makes the block clearer, and means you don't accidentally write:
for (int counter = 0; counter < 6; counter++)
Console.WriteLine("{0,5}{1,8}", counter, array[counter]);
Console.WriteLine("----"); // This isn't part of the for loop!
4) Your switch statement doesn't have a default case - so if the user types anything other than "yes" or "no" it will just ignore them and quit. You might want to have something like:
bool keepGoing = true;
while (keepGoing)
{
switch (answer)
{
case "yes":
Console.WriteLine("===============================================");
Console.WriteLine("please enter the array index you wish to get the value of it");
int index = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("===============================================");
Console.WriteLine("The Value of the selected index is:");
Console.WriteLine(array[index]);
keepGoing = false;
break;
case "no":
Console.WriteLine("===============================================");
Console.WriteLine("HAVE A NICE DAY SIR");
keepGoing = false;
break;
default:
Console.WriteLine("Sorry, I didn't understand that. Please enter yes or no");
break;
}
}
5) When you've started learning about LINQ, you might want to come back to this and replace your for loop which sums the input as just:
// Or decimal, of course, if you've made the earlier selected change
double sum = input.Sum();
Again, this is fairly advanced - don't worry about it for now!
C# does not have a message box that will gather input, but you can use the Visual Basic input box instead.
If you add a reference to "Microsoft Visual Basic .NET Runtime" and then insert:
using Microsoft.VisualBasic;
You can do the following:
List<string> responses = new List<string>();
string response = "";
while(!(response = Interaction.InputBox("Please enter your information",
"Window Title",
"Default Text",
xPosition,
yPosition)).equals(""))
{
responses.Add(response);
}
responses.ToArray();
Try:
array[i] = Convert.ToDouble(Console.Readline());
You might also want to use double.TryParse() to make sure that the user didn't enter bogus text and handle that somehow.
I've done it finaly check it and if there is a better way tell me guys
static void Main()
{
double[] array = new double[6];
Console.WriteLine("Please Sir Enter 6 Floating numbers");
for (int i = 0; i < 6; i++)
{
array[i] = Convert.ToDouble(Console.ReadLine());
}
double sum = 0;
foreach (double d in array)
{
sum += d;
}
double average = sum / 6;
Console.WriteLine("===============================================");
Console.WriteLine("The Values you've entered are");
Console.WriteLine("{0}{1,8}", "index", "value");
for (int counter = 0; counter < 6; counter++)
Console.WriteLine("{0,5}{1,8}", counter, array[counter]);
Console.WriteLine("===============================================");
Console.WriteLine("The average is ;");
Console.WriteLine(average);
Console.WriteLine("===============================================");
Console.WriteLine("would you like to search for a certain elemnt ? (enter yes or no)");
string answer = Console.ReadLine();
switch (answer)
{
case "yes":
Console.WriteLine("===============================================");
Console.WriteLine("please enter the array index you wish to get the value of it");
int index = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("===============================================");
Console.WriteLine("The Value of the selected index is:");
Console.WriteLine(array[index]);
break;
case "no":
Console.WriteLine("===============================================");
Console.WriteLine("HAVE A NICE DAY SIR");
break;
}
}
Add the input values to a List and when you are done use List.ToArray() to get an array with the values.
of course....Console.ReadLine always return string....so you have to convert type string to double
array[i]=double.Parse(Console.ReadLine());
readline is for string..
just use read