I am switching from Python to C# and I am having trouble with the ReadLine() function. If I want to ask a user for input Python I did it like this:
x = int(input("Type any number: "))
In C# this becomes:
int x = Int32.Parse (Console.ReadLine());
But if I type this I get an error:
int x = Int32.Parse (Console.ReadLine("Type any number: "));
How do I ask the user to type something in C#?
You should change this:
int x = Int32.Parse (Console.ReadLine("Type any number: "));
to this:
Console.WriteLine("Type any number: "); // or Console.Write("Type any number: "); to enter number in the same line
int x = Int32.Parse(Console.ReadLine());
But if you enter some letter(or another symbol that cannot be parsed to int) you will get an Exception. To check if entered value is correct:
(Better option):
Console.WriteLine("Type any number: ");
int x;
if (int.TryParse(Console.ReadLine(), out x))
{
//correct input
}
else
{
//wrong input
}
Starting from C# 7 you can use inline variable declaration (out variables):
Console.WriteLine("Type any number: ");
if (int.TryParse(Console.ReadLine(), out var x)) // or out int x
{
//correct input
}
else
{
//wrong input
}
Console.WriteLine("Type any number");
string input = Console.ReadLine();
int x;
if (int.TryParse(input, out x))
{
//do your stuff here
}
else
{
Console.WriteLine("You didn't enter number");
}
Console.WriteLine("Type any number: ");
string str = Console.ReadLine();
Type a = Type.Parse(str);
where Type is Data Type you want to cast user input to.
I suggest reading few books on C# fundaments before turning to forums.
To be more generic I would suggest you to make an additional object ( because you cannot extend static objects in C# ) to behave like you've specified.
public static class ConsoleEx
{
public static T ReadLine<T>(string message)
{
Console.WriteLine(message);
string input = Console.ReadLine();
return (T)Convert.ChangeType(input, typeof(T));
}
}
Of course you this code is not error free because it does not contains any constraints about the output type but still It will cast into some types without any problems.
For example. Using this code :
static void Main()
{
int result = ConsoleEx.ReadLine<int>("Type any number: ");
Console.WriteLine(result);
}
>>> Type any number:
<<< 1337
>>> 1337
Check this online
try this
Console.WriteLine("Type any number: ");
int x = Int32.Parse (Console.ReadLine());
Related
So, I am learning C#, and to practice, I have been trying to make a math solver, so the way I did it, is 1- I present the math question, 2- I receive user-input of the solution, 3- I compare the user's answer to my answer using an if statement, now, I am trying to add a console menu to add different divisions (multiplication/division/sub./add.), i have successfully added the menu, however I am not able to move onto inputting the numbers, the error I get is http://prntscr.com/ohru2i, how can I fix it?
I have tried putting Console.clear(), I have also tried to use break;, but none of them worked
using Figgle;
using System;
using System.Threading;
public class MainClass
{
public static void Main()
{
Console.Title = $"The Math Solver | Correct = 0 | Wrong = 0";
char choice;
for (; ; )
{
do
{
Console.WriteLine("Choose Method:");
Console.WriteLine(" 1. Multiplication");
Console.WriteLine(" 2. Division");
Console.WriteLine(" 3. Addition");
Console.WriteLine(" 4. Subtraction");
Console.WriteLine(" 5. Find the Remainder");
Console.WriteLine("Press Q to Exit ");
do
{
choice = (char)Console.Read();
} while (choice == '\n' | choice == '\r');
} while (choice < '1' | choice > '5' & choice != 'q');
if (choice == 'q') break;
Console.WriteLine("\n");
Console.Clear();
switch (choice)
{
case '1':
{
Console.WriteLine(
FiggleFonts.Standard.Render("Multiplication"));
int milliseconds2 = 2000;
Thread.Sleep(milliseconds2);
int correctAnswers = 0;
int WrongAnswers = 0;
int Number1;
int Number2;
int myInt2;
while (true)
{
Console.WriteLine("Write the first number to multiply");
Number1 = int.Parse(Console.ReadLine());
Console.WriteLine("Write the second number to multiply");
Number2 = int.Parse(Console.ReadLine());
Console.WriteLine($"Write the answer of {Number1} * {Number2}");
myInt2 = int.Parse(Console.ReadLine());
if (myInt2 == Number1 * Number2)
{
Console.WriteLine(
FiggleFonts.Standard.Render("Correct!"));
correctAnswers++;
Console.Title = $"The Math Solver | Correct = {correctAnswers} | Wrong = {WrongAnswers}";
}
else
{
Console.WriteLine(
FiggleFonts.Standard.Render("Wrong"));
WrongAnswers++;
Console.Title = $"The Math Solver | Correct = {correctAnswers} | Wrong = {WrongAnswers}";
}
int milliseconds3 = 2000;
Thread.Sleep(milliseconds3);
Console.Clear();
}
}
}
}
}
The error message I get is http://prntscr.com/ohru2i
You're getting the error when converting a number to a string because console.Read() consumes the first character from the standard input, but leaves the line break from the user hitting enter. Therefore, the next time you go to read a line from the console, you just get a blank line, which is not a valid string for number conversion.
Solution is to use Console.ReadLine() and either look at the first character by indexing the string, or replace choice character constants with string constants.
I am trying to make a program to sum numbers until the user enter OK.
The program make the sum, but return a bad result.
i'm not sure where is my error...
int sum = 0;
Console.WriteLine("Enter number:");
int num = Convert.ToInt32(Console.ReadLine());
while (Console.ReadLine() != "OK")
{
sum += num;
}
Console.WriteLine(sum);
you don't keep the number the use enter in the while loop.
you need to input the readline to a variable.
var num = Console.Readline();
sum += num; //parse first
Inside your while loop you need to update num:
int num = Convert.ToInt32(Console.ReadLine());
while (Console.ReadLine() != "OK")
{
num = Int32.Parse(Console.ReadLine());
sum += num;
}
Also just as a note, if you need your program to be a little safer, you can you use the following:
int num;
if(Int32.TryParse(Console.ReadLine(), out num)) {
//do something..
}
else {
//do something else.. like end program, throw exception etc.
}
Int32.TryParse:
Converts the string representation of a number to its 32-bit signed
integer equivalent. A return value indicates whether the conversion
succeeded
This way you can do something in the instance that the input string was not a valid conversion. Example: if someone input cat, which can not be converted to an int, it would crash your program without the TryParse.
You need to input the number once per iteration, and store it each time. So each value retrieved from Console.ReadLine() needs to be captured in an assignment statement, then converted to a number if it is not "OK".
I think you're after this:
int sum = 0;
string input;
Console.WriteLine("Enter number: ");
while ((input = Console.ReadLine()) != "OK")
{
int inputNum = Convert.ToInt32(input);
sum += num;
Console.WriteLine("Enter number: ");
}
The statement (input = Console.ReadLine() assigns the user input to the input variable, then the assignment statement returns the value of input. Then that value is compared against OK.
An alternative way to get input, then check it is:
Console.WriteLine("Enter number: ");
input = Console.ReadLine()
while (input != "OK")
{
...
Console.WriteLine("Enter number: ");
input = Console.ReadLine()
}
int sum = 0;
Console.WriteLine("Enter number:");
int num = int.Parse(Console.ReadLine());
while (sum< num)
{
sum++;
}
Console.WriteLine(sum);
I need help with some of my code for a game calculator. So I wrote all this code, but the IF/THEN statement is acting weird.
Screenshot:
-
I typed in P and it should have gone to the ELSE part of the code, but instead it continued onto the if part. Please help!
{
class MainClass
{
public static void Main(string[] args) // IF YOU ARE TO REWRITE FROM MY SOURCE, ALL ORIGINAL CREDITORS MUST GO INTO THE CREDITS!
{
double num01;
double num02;
double num03;
double num04;
double num05;
double num06;
string CD = null;
string P = null;
string answer = null;
Console.Write("Diogenes's Calculator 1.0\n\nCredits: DoS (#57714)\n DZ(#54689)");
Console.WriteLine();
Console.WriteLine();
Console.Write("Hello! Would you like Charity Donation or Propaganda Calculator? (CD or P): ");
Console.ReadLine();
answer = Convert.ToString();
if(answer == CD) {
Console.WriteLine();
Console.Write("Howmuch influence does the target have?: ");
num01 = Convert.ToDouble(Console.ReadLine());
Console.Write("Howmuch is the cost of Charity Donatins? (Gold): ");
num02 = Convert.ToDouble(Console.ReadLine());
Console.Write("What % of influence does Charity Donation give (Made if value does change)?: ");
num03 = Convert.ToDouble(Console.ReadLine());
Console.Write(num02 + num03);
Console.ReadKey();
} else if(answer == P) {
answer = Convert.ToString();
Console.WriteLine();
Console.Write("Howmuch influence does the target have?: ");
num04 = Convert.ToDouble(Console.ReadLine());
Console.Write("Howmuch influence do you want the target to have?: ");
num05 = Convert.ToDouble(Console.ReadLine());
Console.Write("What % of influence does Propaganda take off (Made if value does change)?: ");
num06 = Convert.ToDouble(Console.ReadLine());
Console.Write(num04 + num05);
Console.ReadKey();
} else {
Console.WriteLine("Looks like you didn't type in CD or P. Buh Bye!");
Console.ReadKey();
}
}
}
}
you are checking if answer is equal to the value stored in the field P, not if answer is equal to the actual string "P". And P the variable is null.
Secondly, you are throwing away your user input here:
Console.ReadLine();
answer = Convert.ToString();
you are reading the console input into nothing, then assigning answer to the Convert object's string representation, which is probably a fully qualified namespace. You want:
answer = Console.ReadLine();
Console.Write("Hello! Would you like Charity Donation or Propaganda Calculator? (CD or P): ");
answer = Console.ReadLine();
if(answer == "CD") {
I am teaching myself c# with the help of a few books and I got curious so I tried building a small console app to get two numbers from user add them together and using an if else statement depending on the result print one of the messages but my code asks for the second number and prints the else statement and the press any key to continue all at the same time without getting my second number or doing the math
using System;
namespace helloworldwcond
{
class Program
{
public static void Main(string[] args)
{
int a;
int b;
int c;
Console.Write("Enter a Number: ");
a = Console.Read ();
Console.Write ("Enter another Number: ");
b = Console.Read ();
c = a + b;
if (c == 7) {
Console.WriteLine("Hello World!");
} else {
Console.Write("We Are DOOMED");
}
// TODO: Implement Functionality Here
Console.Write ("Press any key to continue . . . ");
Console.ReadKey (true);
}
}
}
The problem is the way you get your input. You should use Console.ReadLine() instead of Console.Read(). The correct code should be:
int a;
int b;
int c;
Console.Write("Enter a Number: ");
a = Int32.Parse(Console.ReadLine());
Console.Write("Enter another Number: ");
b = Int32.Parse(Console.ReadLine());
// The rest are the same
Why use Console.ReadLine() instead of Console.Read()?
Console.Read() return the ASCII code of the input character. For example, you enter 4 for a, then what you get is a = 52, not a = 4, because 52 is the ASCII code of character 4.
Console.Read() only read 1 character from the input stream. So, when you enter value for a, you type: 3 enter. At that time, your input stream has 2 characters: 3 and enter. Then, when you call Console.Read() for b, it will read the next character, which is enter, and go on. It's the reason for the behavior of your program.
In conclusion, you should use Console.ReadLine() to read a line, then parse it as you want.
To know more about the difference between that 2 functions, please read this post.
Console.Read returns the next character as an integer.
So a 0 is ASCII 48, so entering a 0 will return 48.
Use Convert.ToInt32() to convert a character to the integer value.
a = Convert.ToInt32(Console.Read());
Of course you may want to also add checking that the character typed is a number. And this will only work for 1 digit numbers.
Either way, probably want to do a Console.ReadLine() instead which will return a string of everything typed until they hit enter. Then convert the string to a number as int.Parse(string value)
Console.Write("Enter a Number: ");
string temp = Console.ReadLine();
a = Int32.Parse(temp); // Or could use
bool isThisANumber = Int32.TryParse(temp, a);
As answered by Mike above, Console.Read returns the ASCII value of the first character in the input. You could use Console.ReadLine instead and parse the string as an integer. Mike has suggested as well while I was posting this.
using System;
namespace helloworldwcond
{
class Program
{
public static void Main(string[] args)
{
int a;
int b;
int c;
Console.Write("Enter a Number: ");
a = int.Parse(Console.ReadLine());
Console.Write("Enter another Number: ");
b = int.Parse(Console.ReadLine());
c = a + b;
if (c == 7)
{
Console.WriteLine("Hello World!");
}
else
{
Console.Write("We Are DOOMED");
}
// TODO: Implement Functionality Here
Console.Write("Press any key to continue . . . ");
Console.ReadKey(true);
}
}
}
Console.Read returns the ascii value of the input given. For a quick and dirty solution try this:
int a;
int b;
int c;
Console.Write("Enter a Number: ");
a = Console.Read() - '0';
Console.Write("Enter another Number: ");
b = Console.Read() - '0';
c = a + b;
if (c == 7)
{
Console.WriteLine("Hello World!");
}
else
{
Console.Write("We Are DOOMED");
}
This is a very simple script I am trying to figure out and I have been looking for a simple answer and can't find it in the forums or in my C# book.
Console.Write("Enter a Number\n");
int input = Convert.ToInt32(Console.ReadLine()); //convert code to an integer
if (!Int32.IsNumber(input)) //if not a whole number input give an error
{
Console.WriteLine("Not an integer");
}
It's just that simple what I'm trying to do. This is a snippet from a bigger code.
Console.Write("Enter a Number\n");
string input = Console.ReadLine(); //get the input
int num = -1;
if (!int.TryParse(input, out num))
{
Console.WriteLine("Not an integer");
}
else
{
...
}
Int.TryParse will return false if the string is not a valid integer and vise versa
I figured out the easiest and best code to get this done from many answers:
Console.Write("\nEnter a Whole Number (Such as 12)\n");
string Input = Console.ReadLine();
char firstChar = Input[0];
bool isNumber = Char.IsDigit(firstChar);
if (!isNumber)
{
Console.WriteLine("Not an integer");
}
else
{
.......
}