Console Application with C# Not Displaying WriteLine if Bool is True - c#

I am just starting to learn C# as my first programming language, so I decided to make a simple question and answer C# console application. The console will ask you a question, and if you get it right it will say "Correct". After a while I got it all to work with no errors, except it never said "Correct"
using System;
namespace Project
{
class MainClass
{
public static void Main (string[] args)
{
byte answer = 0;
Console.WriteLine ("What is 27+4?");
Console.ReadLine ();
if (answer == 31)
{
bool answerCorrect = true;
if (answerCorrect == true)
Console.WriteLine ("Correct!");
}
}
}
}
Thanks for all your help!

Because Console.ReadLine() reads your input(as a string), but it's not assigned to your variable answer. To make your program work, change the line to:
answer = byte.Parse(Console.ReadLine());
But remember to improve your code, for example, using int instead of byte, and the code in if (answer == 31) block can be shorter, etc. Good luck.

You must store the string return value from ReadLine and parse that. Like so:
byte answer = 0;
Console.WriteLine("What is 27+4?");
string s = Console.ReadLine();
if (byte.TryParse(s, out answer) && answer == 31)
{
bool answerCorrect = true;
if (answerCorrect == true)
Console.WriteLine("Correct!");
}

Try this one.
using System;
namespace Project
{
class MainClass
{
public static void Main (string[] args)
{
byte answer = 0;
Console.WriteLine ("What is 27+4?");
answer = byte.Parse(Console.ReadLine ());
if (answer == 31)
{
bool answerCorrect = true;
if (answerCorrect == true)
Console.WriteLine ("Correct!");
}
}
}
}

Console.Readline() returns the string value entered by the user, so firstly capture that input.
string input = Console.ReadLine ();
Next check if the input is correct by using String.Equals method to compare
if(input.Equals("31"))
and lastly there's no need to create and assign a value to an answerCorrect variable since if the code goes into the if statement the answer is correct, so just Console.WriteLine ("Correct!") inside.

First I would use int instead of byte. Then you have to assign the userinput to your variable answer. The type int provides a method called .Parse(string s) which tries to convert the string you get from Console.ReadLine() to an int. Of course it fails if the input is something like "hello". That's a good thing to look at to improve later.
Your use of bool answerCorrect may be correct, but remember: the comparison always "returns" a bool, so you don't really need an extra one.
Lastly, you're missing one important line Console.Read(); at the very end in your main-method. It's a bit cheaty but your program then waits for a userinput and the console window stays open and you can actually see what's in there.
static void Main(string[] args)
{
int answer = 0;
Console.WriteLine("What is 27 + 4?");
answer = int.Parse(Console.ReadLine());
if (answer == 31)
{
Console.WriteLine("Correct!");
}
else //I added this part for beauty reasons
{
Console.WriteLine("Incorrect!");
}
Console.Read();
}
I recommend you to have a look at while to run your program as long as the user gives the wrong answer and try..catch to accept "hello" as an input but handle it differently, to improve even more.
Good job though for your first C# application.

Related

How to write a function that takes an integer as a parameter and calculates and returns the squared value

Ahoy! I have just started methods but I am a tad confused when it comes to methods with math. First post so be nice :) I'm aware I out in NumberToSquare way too many times!
Write a program that asks the user to enter a number. In your program write a function called SquareValue that takes an integer parameter and calculates the square of integer parameter and returns this squared value. Your program should take this returned square value and display it. An example of the output is:
Please enter a number to square: 8
/ 8 squared is: 64
What I have so far is not so comprehensible. I thought along a few different avenues and was unsure as to what to delete. Help please.
namespace SquareValue
{
class Program
{
static void Main(string[] args)
{
int number=NumberToSquare();
SquareValue(NumberToSquare * NumberToSquare);
string output;
Console.ReadKey();
}
public int SquareValue(NumberToSquare, NumberToSquare);
{
int result = NumberToSquare * NumberToSquare;
return result;
Console.WriteLine("{0} squared is "+result");
}
public int NumberToSquare()
{
Console.WriteLine("Please enter a number to square: ");
int NumberToSquare = Console.ReadLine();
return NumberToSquare;
}
}
I see no reason to over complicate this:
public int Square(int x)
{
return (x * x);
}
or
public int Square(int x)
{
return Math.Pow(x,2);
}
Or just use Math.Pow as it exists with 2 as the Power Of number.
You seem very green on programming and I'm not sure SO is a place to go to learn the basics, but I'll run through what you've done and explain what's going wrong.
Your original program concept is fine but there are many issues with basic syntax. I understand you mightn't be familiar with reading compiler errors so I'll explain the errors that I see just reading through the code...
You put a ; at the end of the SquareValue(..., ...) method which teeminates the declaration so the body in braces isn't part of the method, then things go haywire later on.
You're not passing in the value captured from the NumberToSquare method...
int number=NumberToSquare();
SquareValue(NumberToSquare * NumberToSquare);
NumberToSquare isn't a defined variable so NumberToSquare * NumberToSquare can't calculate, what you'd want is number * number where `number is the value entered by the user.
Your definition of int SquareValue(NumberToSquare, NumberToSquare) expects two parameters although you haven't speified the type. It should be
int SquareValue(int NumberToSquare, int NumberToSquare)
but you have the same variable declared twice which is another error and then you aren't passing two parameters anyway. You want to multiply a number by itself therefore you only have a single source number so why declared two parameters? You need a single parameter method
int SquareValue(int NumberToSquare)
and call like this
int number=NumberToSquare();
SquareValue(number);
Now the SquareValue() method returns an int but you never capture it in the calling code and display the result in the method. Follow the idea in this app that the Main method will do all the orchestration and display, but the SquareValue() method should ONLY do a calculation and not any I/O. I'd also rename the NumberToSquare() method a as what is actually happening ... GetNumberToSquareFromUser().
And there's also a stray " before the closing bracket.
Console.WriteLine("{0} squared is " + result");
And you defined a string output variable which is never used.
And your methods need to be static because main(..) is a static method, not instance. If you declare a Squaring class and instantiated it then you could call non static methods from that.
Also ReadLine() returns a string which can't be assigned to an int.
And finally the result line is implicitly using String.Format behind the scenes but you haven't specified the original number for the {0} token. You could also use interpolation. You could do either of these
Console.WriteLine("{0} squared is " + result, number);
Console.WriteLine($"{number} squared is " + result);
So here's your program revised
class Program
{
static void Main(string[] args)
{
int number = GetNumberToSquareFromUser();
int result = SquareValue(number);
Console.WriteLine("{0} squared is " + result, number);
Console.ReadKey();
}
public static int SquareValue(int numberToSquare)
{
return numberToSquare * numberToSquare;
}
public static int GetNumberToSquareFromUser()
{
Console.WriteLine("Please enter a number to square: ");
int NumberToSquare = int.Parse(Console.ReadLine());
return NumberToSquare;
}
}
I hope this help, I know it's alot to take in, but I hope you take the time to read and really understand rather than just blindly submit the revised version.
When writing your methods, make them reusable. When you start using a method to output to the console in addition to its primary purpose (i.e. to square a number), its re-usability becomes minimal. It is much better to keep specific code in your main method, and put sub tasks into separate methods, such as squaring a number. Now, whenever you need to square a number, you already have a perfectly good method for that.
I didn't handle the case for users entering bad input, but that can be done in the else of the TryParse if block.
static void Main(string[] args)
{
int squredNum = 0;
int NumberToSquare = 0;
Console.WriteLine("Please enter a number to square: ");
if(int.TryParse(Console.ReadLine(), out NumberToSquare))
{
squredNum = SquareValue(NumberToSquare);
Console.WriteLine("{0} squared is {1}", NumberToSquare, squredNum);
}
Console.ReadKey();
}
static int SquareValue(int numberToSquare)
{
return numberToSquare * numberToSquare;
}
p.s. I would not recommend using Math.Pow() to square a number. No need to kill a fly with a bazooka!
Here is an example of such program with robust handling:
using System;
namespace ConsoleApp1
{
internal static class Program
{
private static void Main(string[] args)
{
while (true)
{
Console.WriteLine("Enter value to square or X to exit");
var line = Console.ReadLine();
if (line == null)
continue;
if (line.Trim().Equals("X", StringComparison.InvariantCultureIgnoreCase))
{
Console.WriteLine("Exitting ...");
break;
}
int result;
if (!int.TryParse(line, out result))
continue;
Console.WriteLine(result * result);
}
}
}
}
See the docs online, understand each statement, write your very own program then as your teacher will likely figure out you didn't pull that solely by yourself :)

How do i check if an input matches a specific letter?

I can't figure out how to check whether the input is a specific letter. I know how to check if it's a specific int/double but when it's a string I don't know what to do.
Any help would be greatly appreciated. I'm just trying to make a basic 3 question quiz that checks whether the user answers with the correct letter (a, b or c) and then adds that to the current score.
class Program
{
static void Main()
{
var a1 = "a";
var a2 = "b";
var a3 = "c";
var qa = 0;
while (qa != 3)
{
if (qa == 0)
{
Console.Write("What is the answer to question 1? ");
var entry1 = Console.Read();
if()
{
}
}
else if (qa == 1)
{
Console.Write("What is the answer to question 2? ");
Console.ReadLine();
}
else if (qa == 2)
{
Console.Write("What is the answer to question 3? ");
Console.ReadLine();
}
}
}
}
For example operator == can't be applied to strings
this is not true. It can be applied:
if(entry.ToString() == a1)
The documentation for the == operator tells us:
For the string type, == compares the values of the strings
another possibility would be to use the String.Equals method
if(entry.ToString().Equals(a1))
EDIT:
Looking closer at your code I realized that you are using Console.Read
which
Reads the next character from the standard input stream.
That means that it returns a char (and only 1).
I guess you want the entire line that the user types in. So you should use ReadLine instead. It returns a string and allows you for a direct comparison
string entry1 = Console.ReadLine();
if(entry == a1)
when you use var for the declaration of types the compiler infers the type and the error becomes obvious at a later stage. you cannot use the == operator on string and char . Read() returns a char so that's why you were not able to compare it in the first place
Note that in "Question 1" you wrote Console.Read(), (not Console.ReadLine()) which returns a char, not a string. So "==" cannot be applied to entry1 and a1 since entry1 will be a char while a1 is a string.
If you compare compatible variables, everything should be fine
string input1;
var input2 = "";
var input3 = 0;
// assign some input values, then compare
// strings
if (input1 == "a") // ok
{ }
if (input2 == "a") // ok
{ }
if (input3 == "a") // not ok, comparing int to string
{ }
// numbers
if (input1 == 1) // not ok, comparing string to int
{ }
if (input3 == 1) // ok
{ }
If you want to, you could try matching the ASCII value of the character by using Console.Read();. This would eliminate the need to press enter. If you were trying to match to uppercase A:
int input = Console.Read();
if (input == (int)char.GetNumericValue(A))
{
Console.WriteLine("True");
Console.Read();
}
else
{
Console.WriteLine("False");
Console.Read();
}

C# If(textbox.text=number) error

I making a quiz in which users would have to enter a number (e.g. 4) into a TextBox then the program would check if the number entered is correct. Unfortunately, I'm having some trouble with this part of the code.
So currently I have this code:
if(textbox1.Text=4)
but the 4 is underlined with the error message:
cannot implicitly convert type 'int' to 'string'.
Can I trouble you all to help me find out what's wrong with my code? Thank you so much!!
Since textbox1.Text is of type string, you have to parse:
int answer;
// TryParse - the value entered can be treated as a valid integer
// answer == correctAnswer - the answer provided is a correct one
if (int.TryParse(textbox1.Text, out answer) && answer == correctAnswer) {
...
}
Please, notice that the implementation tolerates leading and traling spaces (typical problem in quizes): if user happens to input "4 " (trailing space) the answer will be accepted providing that correctAnswer == 4
if(textbox1.Text == Convert.ToString(4))
or
if(textbox1.Text == "4")
You need to parse to int
if(Int32.Parse(textbox1.Text) == 4)
You are comparing a string (textbox1.Text) with an integer (4). To make this work you have to compare same data types. Some options:
if(textbox1.Text == "4")
or
if(textbox1.Text == 4.ToString())
or
if(int.Parse(textbox1.Text) == 4)
NOTE: In the last option you can get an exception if the text in the textbox is not a number. So if you want to convert to integer than I would suggest:
int guessedNumber;
Int32.TryParse(textbox1.Text, out guessedNumber);
if(guessedNumber == 4)
You are trying to compare a string with an int.
You need to use if(textbox1.text == "4")
also note the double == for comparisons
The Text property is of type string and 4 is an int so the comparison results in a compile time error.
Use the following code to perform the check.
if (int.Parse(textbox1.Text) == 4)
{
// do something
}
If you're unsure whether the user is going to provide the input correctly or if you haven't set any validations on the model, then you should parse the input and then check whether the user entered 4. Here's the rextester link
//Rextester.Program.Main is the entry point for your code. Don't change it.
//Compiler version 4.0.30319.17929 for Microsoft (R) .NET Framework 4.5
using System;
namespace Rextester
{
public class Program
{
public static void Main(string[] args)
{
var input = "hello 4";
// var input = "4";
int number;
var isNumber = int.TryParse(input, out number);
if (isNumber)
{
if (number == 4)
{
Console.WriteLine("The Number is 4");
}
else
{
Console.WriteLine("The Number isn't 4");
}
}
else
{
Console.WriteLine("Not a valid number");
}
}
}
}
if(textbox1.Text == "4")
{
//Do Something
}
One way or another, you have to make sure both values are to make sure you are comparing two values "==" (not "=", unless u want to change the value) and that both values are same data type

Why does it keep looping at Would You Like To Try Again?

Ok so I am trying to run this
static void Main(string[] args)
{
string ans;
bool Operation = false;
Console.WriteLine("Hello user, would you like to do maths today? Write yes or no.");
ans = Console.ReadLine();
ans.ToLower();
do
{
Console.WriteLine("Would you like to try again?");
string answerFinal = Console.ReadLine();
answerFinal.ToLower();
if (answerFinal == "yep")
{
Operation = true;
}
else
{
Operation = false;
}
}
while (Operation == true);
}
However, it keeps looping at Would You Like To Try Again if I keep pressing yes, any ideas why? I think it has to do with Try Catch, can someone tell me how to use them in this instance?
ans.ToLower();
doesn't modify anything in ans, it returns a copy of ans as lowercase. You need to do this:
ans = ans.ToLower();
For each time you use .ToLower(), like for answerFinal.
The problem is that you are using the same variable here
Console.WriteLine("Hello user, would you like to do maths today? Write yes or no.");
ans = Console.ReadLine();
ans.ToLower();
and here
Console.Clear();
Console.WriteLine("Please select from one of the operations!");
Console.WriteLine("Either write Multiplication, Division, Addition or Subtraction.");
ans = Console.ReadLine();
ans.ToLower();
So by the time the do-while starts again, the value in ans has already changed and isn't yes any longer so it just goes to the last statement. Change the second part of the code to
Console.Clear();
Console.WriteLine("Please select from one of the operations!");
Console.WriteLine("Either write Multiplication, Division, Addition or Subtraction.");
string answer = Console.ReadLine();
answer = answer.ToLower();
if (answer == "multiplication")
{
//other statements
Also, change
ans.ToLower();
to
ans = ans.ToLower();
and the same for the likes
You assign your ans variable to a bunch of different values in your loop, none of them being "yes". Then when you come back into the do loop again you fail the first condition statement if (ans == "yes"). This will be false, causing you to keep skipping over that block of code, landing you right back to the "Would you like to try again" line.

Convert String to int in C#

I am trying to write a simple program that asks the user to enter a number and then I will use that number to decide what the cost of the ticket will be for their given age. I am having trouble when trying to convert the string to int. Otherwise the program layout is fine. Any suggestions?
thanks
using System;
class ticketPrice
{
public static void Main(String[] args)
{
Console.WriteLine("Please Enter Your Age");
int input = Console.ReadLine();
if (input < 5)
{
Console.WriteLine("You are "+input+" and the admisson is FREE!");
}
else if (input > 4 & input < 18)
{
Console.WriteLine("You are "+input+" and the admission is $5");
}
else if (input > 17 & input < 56)
{
Console.WriteLine("You are "+input+" and the admission is $10");
}
else if (input > 55)
{
Console.WriteLine("You are "+input+" and the admission is $8");
}
}
}
Try the int.TryParse(...) method. It doesn't throw an exception.
http://msdn.microsoft.com/en-us/library/f02979c7.aspx
Also, you should use && not & in your conditions. && is logical AND and & is bitwise AND.
For easy parsing of strings to integers (and other number types), use that number type's .TryParse(inputstring, yourintegervariable) method. This method will output a Boolean (True/False), letting you know whether the operation passed or failed. If the result is false, you can give an error message before going any further (don't have to worry about crashing your program).
Previous text concerning switch statements has been removed
In C#, you need to use the && operator for logical AND. & is not the same and may not work the way you believe it will.
I suggest to use the Int32.TryParse() method. Further I suggest to refactor your code - you can make it much cleaner (assuming this is not just example code). One solution is to use a key value pair list to map from age to admission.
using System;
using System.Collections.Generic;
using System.Linq;
static class TicketPrice
{
private static readonly IList<KeyValuePair<Int32, String>> AgeAdmissionMap =
new List<KeyValuePair<Int32, String>>
{
new KeyValuePair<Int32, String>(0, "FREE!"),
new KeyValuePair<Int32, String>(5, "$5."),
new KeyValuePair<Int32, String>(18, "$10."),
new KeyValuePair<Int32, String>(56, "$8.")
};
public static void Main(String[] args)
{
Console.WriteLine("Please Enter Your Age!");
UInt32 age;
while (!UInt32.TryParse(Console.ReadLine(), out age)) { }
String admission = TicketPrice.AgeAdmissionMap
.OrderByDescending(pair => pair.Key)
.First(pair => pair.Key <= age)
.Value;
Console.WriteLine(String.Format(
"You are {0} and the admission is {1}",
age,
admission));
}
}
I used an unsigned integer to prevent entering negative ages and put the input into a loop. This way the user can correct an invalid input.
int number = int.Parse(Console.ReadLine());
Be aware that this will throw an exception if they enter an invalid number.
The first thing you need to do is change your input variable to a string:
string input = Console.ReadLine();
Once you have that, there are several ways to convert it to an integer. See this answer for more info:
Better way to cast object to int

Categories

Resources