okay so, I have been asked to write a console application for a theater ticket system. A user will type in the number of seats required, and the area of the theater chosen (using the code number 1-4 to represent the seating area chosen) The program should work out and display the cost of the tickets, based on the pricing plan shown below
Area Code price
Stalls 1 £24
Grand circle 2 £30
Upper circle 3 £27
Gallery 4 £20
I've so far came up with the following, But it's got an error to do with string + Int conversions under the IF Statements section, this is probably very easy to fix, but I'm new to programming so i'm unsure how to resolve it:
//Declare variables and constants
int iSeatNum;
int iArea;
int iCost;
int iTotalCost;
//Ask the user how many seats they require
Console.WriteLine("How many seats would you like to purchase?");
iSeatNum = Convert.ToInt32(Console.ReadLine());
//Ask the user what area they would like to be in
Console.WriteLine("Where would you like to sit? Please enter 1 for Stalls, 2 for Grand Circle, 3 for Upper Circle or 4 for Gallery");
iArea = Convert.ToInt32(Console.ReadLine());
**if (iArea = "1")**
{
iCost = 24;
}
//Clarify information & work out
Console.WriteLine("You are buying " + iSeatNum + " Seats at " + iArea);
iTotalCost = iSeatNum * iCost;
Console.WriteLine("Your total ticket cost is " + iTotalCost);
//Prevent from closing
Console.WriteLine("Press any key to close");
Console.ReadKey();
if (iArea = "1")
iArea is an integer, "1" is a string. So you cannot compare those two. You should compare with the integer 1 instead. Also note that a single equals symbol (=) is an asignment, and not a comparison. You will want to use two there: ==
if (iArea == 1)
now it displays a further error, when I put iTotalCost = iSeatNum * iCost; it comes up the error of "Use of unassigned local variable iCost" Any idea how I fix this?
The problem is that you declare the variable iCost at the beginning, but never safely assign any value to it before using it. You do assign a value when iArea equals to 1, but for all other cases, the variable remains uninitialized. Of course the compiler doesn’t know that you will end up typing in 1 when the program runs for testing, and that’s not a safe thing anyway. So it requires you to initialize your variable with anything instead.
So at the beginning, you can just say int iCost = 0; to fix this.
Well "1" is a string, not int.
if (iArea == 1)
Because you have already converted you string (the Console.ReadLine() return a string) into number using:
iArea = Convert.ToInt32(Console.ReadLine());
you can compare it as number using:
if (iArea == 1)
note the == instead of =, the single is used for assignment, the double for comparison.
if (iArea = "1")
This doesn't make sense. First of all you're using the assignment equals operator. You're attempting to assign iArea the value of "1". Instead, you need the logical equality operator == which will return true or false depending on whether the first operand is equal to the second operand.
Second, you have already converted the string value read from the console to a strongly typed integer. So you need to write your if statement as follows:
if (iArea == 1)
String strArea =Console.ReadLine();
if (strArea.Equals("1"))
{
iCost = 24;
}
or
int iArea = Convert.ToInt32(Console.ReadLine());
if (iArea == 1))
{
iCost = 24;
}
Related
I am new to programming in C# and i'm currently doing an exercise that looks like this:
Read the user's first and last name and save this in variables
Welcome the user
Ask the user about their age this year and save this in a variable with the appropriate data type
Calculate previous days the person has lived based on the specified age (age multiplied by 365) and present this.
So my code is working fine, but i would really appreciate if someone could explain the convert thing. I've been making alot of google searches and reading, but i can't seem to understand how it works.
int age = Convert.ToInt32(Console.ReadLine());
Can someone break this down for me for my code?
Thanks!
Console.Title = "Programming in C # - Exercise 1";
// Here the system asks the user to enter their full name.
Console.WriteLine("System: Enter your full name: ");
// Here I declare a variable and assign it a value.
string name = Console.ReadLine();
// Here the system welcomes the user.
Console.WriteLine("System: Welcome " + name + "!");
// Here the system asks how old the user is.
Console.WriteLine("System: How old are you?");
// This is the part i would like to have explained for me.
int age = Convert.ToInt32(Console.ReadLine());
// Here I declare a variable and calculate age in days.
int ageInDays = age * 365;
// Here the system answers.
Console.WriteLine("System: " + age + "?!" + " That means you are " + ageInDays + " days old!");
// Waiting to close the program.
Console.ReadLine();
Although you have a understanding now I'd like to point out that developers/coders should always expect the unexpected e.g. a user enters the wrong type such as for age a value that can not be converted to a integer or the case of name, they simply press enter without entering a name.
So for checking in this case for name being entered use string.IsNullOrWhiteSpace. For integer type, consider using int.TryParse.
In regards to concatenating string values or string values say with integers consider looking at string interpolation, this can be coder preference as some will like to string someString + anotherString or if using strings only there is String.Concat and StringBuilder Class.
Below is a slightly modified version of your code. Since you are just starting out, tuck this away for later or consider learning from this now than later.
using System;
namespace Exercise1
{
class Program
{
static void Main(string[] args)
{
Console.Title = "Programming in C # - Exercise 1";
Console.WriteLine("System: Enter your full name: ");
string fullName = Console.ReadLine();
/*
* Never assume a value for name has been entered
* https://learn.microsoft.com/en-us/dotnet/api/system.string.isnullorwhitespace?view=net-5.0
*/
if (!string.IsNullOrWhiteSpace(fullName))
{
/*
* Note original code concatenated name variable with text, you can also use string interpolation
* https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/tokens/interpolated
*/
Console.WriteLine($"System: Welcome {fullName}!");
}
else
{
Console.WriteLine("System: Welcome no name given!");
}
Console.WriteLine("System: How old are you?");
string ageInput = Console.ReadLine();
/*
* int.TryParse, better than Convert.ToInt32 which is recommended in the remark section
* for documentation for Convert.ToInt32.
*
* https://learn.microsoft.com/en-us/dotnet/api/system.int32.tryparse?view=net-5.0
*
*/
if (int.TryParse(ageInput, out var age))
{
int ageInDays = age * 365;
/*
* Note original code concatenated name variable with text, you can also use string interpolation
* https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/tokens/interpolated
*/
Console.WriteLine($"System: {age}?! That means you are {ageInDays} days old!");
}
else
{
Console.WriteLine("No age provided or the value was not a valid integer");
}
Console.WriteLine("Press any key to close this program");
Console.ReadLine();
}
}
}
You read a line from the console and then convert it to a 32bit integer, which is then stored in the variable age.
However this is dangerous, as you do not check if any non numerical characters are given by the user. What does your application do if the user inputs "Foo"? In your application this does not seem like a big problem, but be aware to check for the input first and then continue if the input is valid.
Console.ReadLine reads input from the console in the form of a string data type. This is a data type which, in very very basic terms, represents text. Under the hood, each character is represented by a code. You may have heard some of these encoding terms before, such as ASCII or UTF. For example, A in ASCII is represented by the number 65. This is also true for numbers. The ASCII code 48 represents the number 0.
We sometimes need to convert the string representation of a number to its actual numerical value. Often for performing mathematical operations and such. To do that, we need to get that "0 which is represented as 48 in ASCII" to a literal 0. This is done by Convert.ToInt32 as you're doing. It reads the string, and says "Oh i'm the text representation of a 0, therefore I will output the number 0".
So in a very brief summary, its taking text representation of a number and changes the data to a literal numerical value.
Console.Realine() in C# gives you a output of string..
So in order to convert to numerical... Convert Function will be useful..
Console.WriteLine("enter your number : ")
Dim number1, number2, number3, largest As Integer
number1 = 2
number2 = 7
number3 = 14
' if 2 > 0 then largest = 2
If number1 > largest Then largest = number1
' if 7 > 2 then largest = 7
If number2 > largest Then largest = number2
' if 14 > 7 then largest = 14
If number3 > largest Then largest = number3
label1.text = largest
Try some formula first.
Assign a default value as the largest value
Let each value entered be tested against the default largest value
If it is larger, then assign the value of the default to the entered value
If it is smaller, ignore it and continue the input
Your final value assigned to the default largest value will be the largest.
So you have a console app and want to ask the user for 5 integers and output the highest?
Dim numberList As New List(Of Int32)
Do
Dim nextNumber As Int32
Do
Console.writeline("Please enter an integer")
Loop Until Int32.TryParse(Console.ReadLIne(), nextNumber)
numberList.Add(nextNumber)
Loop Until numberList.Count = 5
' easiest way:
Dim maxNumber = numberList.Max()
' learning way:
maxNumber = numberList(0)
For Each num In numberList
If num > maxNumber Then maxnumber = num
Next
Console.WriteLine($"Max-Number is: {maxNumber}")
You can use Math.Max
int number1 = 2, number2 = 7, number3 = 15;
label1.text = Math.Max(Math.Max(number1, number2), number3));
This is a C# example with comments. It will display you higest number entered. It does not keep all the numbers. If you like you like to store all number you can create an array to store them in.
int higestNumber = int.MinValue;//here the higest number willbe held, first value is lowest possible integer
int newNumber;//temp value for current number eneted by the user
for(int i = 0; i < 5; i++)//cycle to enter 5 numbers
{
Console.WriteLine("Enter number " + (i+1));// message to the user (i+1) so its starts from 1 and not 0
newNumber = int.Parse(Console.ReadLine());//entering number by the user
if (newNumber > higestNumber)//checking if the new number is higer then the old one
higestNumber = newNumber;//storing the new higer number
}
Console.WriteLine("Higest number is: " + higestNumber);//displaying higest number`
Here is a vb version as well
Private Shared Sub Main(ByVal args As String())
Dim higestNumber As Integer = Integer.MinValue 'here the higest number willbe held, first value is lowest possible integer
Dim newNumber As Integer 'temp value for current number eneted by the user
For i As Integer = 0 To 5 - 1 'cycle to enter 5 numbers
Console.WriteLine("Enter number " & i + 1) ' message to the user (i+1) so its starts from 1 and not 0
newNumber = Integer.Parse(Console.ReadLine()) 'entering number by the user
If newNumber > higestNumber Then higestNumber = newNumber 'checking if the new number is higer then the old one
'storing the new higer number
Next
Console.WriteLine("Higest number is: " & higestNumber) 'displaying higest number
End Sub
I used a List(Of T). This is a class available in the .Net framework https://learn.microsoft.com/en-us/dotnet/api/system.collections.generic.list-1?view=net-5.0 It is a bit like an array except you don't have to know the size before you start. You don't have to worry about indexes because the .Add method will add at the end of the list. The T stands for Type, in our case, an Integer.
Define a variable to hold the user input.
We want 5 numbers from the user so we set up a loop to run 5 times. (It could be i = 1 To 5, just habit that I use 0 To 4)
The message to write a number will appear 5 times. However, what if the user doesn't enter a number? Our list will only accept Integers. We must test the user input to make sure it is an Integer. Use Integer.TryParse https://learn.microsoft.com/en-us/dotnet/api/system.int32.tryparse?view=net-5.0#System_Int32_TryParse_System_String_System_Int32__ We are using the first Overload.
.TryParse is a very clever Function. It checks the String input, in our case, Console.ReadLine, to see if it can be converted to an Integer. If it can the Function returns True and Our Do loop will end. If False the code inside the Do loop will run and we ask the user to try again. Note that this does not effect the outer For loop so we will still get 5 numbers.
.TryParse does one more thing. When it is successful converting the input String to an Integer, it puts the value into the second parameter, in our case, an Integer called input.
The last line of the For loop adds the successfully converted string to the list.
Finally we display the result to the user. I used and interpolated string indicated by the $. This allows you to include variables or expressions right in the string as long as they are surrounded by braces. { }
We used an Extension Method of List(Of T), .Max. You can see this listed in the link I gave you for List(Of T)
Sub Main()
Dim lst As New List(Of Integer)
Dim input As Integer
For i = 0 To 4
Console.WriteLine("Enter a whole number")
Do Until Integer.TryParse(Console.ReadLine, input)
Console.WriteLine("Sorry, not a whole number. Try Again.")
Loop
lst.Add(input)
Next
Console.WriteLine($"The highest number you entered is {lst.Max}")
Console.ReadKey()
End Sub
The explanation is longer than the code. Do check out the links. It is good to start to learn how to read Microsoft documentation. I always found the Remarks section and the examples most helpful. If you are working in vb be sure to select it with the first drop down arrow on the right side of the page. This will show the examples in vb.
I am very new to C# and I am having some issues. I have been trying for a while now and I cant seem to get it right. I think I have the idea but I just don't know how to make it work. There aren't any examples in the chapters of my book either. I need to "create an application that reads an integer, then determines and displays whether it’s odd or even. Have the user enter an integer and output to the console: The number you have entered is: input value + even or odd" I'm hoping I can get some help here. Not looking for someone to just do the work either. If you can explain it, please do!
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Student_Challenge_Lab_2
{
class Program
{
// main method begins the execution of C# program
static void Main(string[] args)
{
int number1; // declares the integer to be added
// following code prompts user to input the two sets of integers
Console.Write("Please enter your integer: ");
number1 = Convert.ToInt32(Console.ReadLine());
int %(number1, );
// the program now tests to see if the integer is even or odd. If the remainder is 0 it is an even integer
if (% == 0)
Console.Write("Your integer is even.", number1);
else Console.Write("Your integer is odd.", number1);
}
} // end main
} // end Student challenge lab 2
Every binary operator should be used in a form:
[argument1] [THE OPERATOR] [argument2]
The % is also a binary operator, which can be used in the same way as + and /. So analogically, if the / operator produces the result of a division operation:
float result = (float)number1 / number2;
the % will produce the remainder in the same fashion:
int remainder = number1 % number2;
All what's left is that numbers that are even produce 0 remainder when modulo against 2 is calculated.
I'm not sure how you've come up with the syntax you're using here
int %(number1, );
You've already defined number1 as an int above. You want to define a new variable that contains the value of your mod operation on number1. So something like:
int remainder = number1 % 2;
Then
if (remainder == 0)
Here, I have done your homework...
The ?? operator is called the null-coalescing operator and is used to define a default value for nullable value types or reference types. It returns the left-hand operand if the operand is not null; otherwise it returns the right operand.
The % operator computes the remainder after dividing its first operand by its second. All numeric types have predefined remainder operators.
I also added a Console.ReadKey so that you can see the output, press any key to end the app.
using System;
namespace Student_Challenge_Lab_2
{
internal class Program
{
// main method begins the execution of C# program
private static void Main(string[] args)
{
// following code prompts user to input the two sets of integers
Console.Write("Please enter your integer: ");
var number1 = Convert.ToInt32(Console.ReadLine());
// the program now tests to see if the integer is even or odd. If the remainder is 0 it is an even integer
Console.Write(number1 % 2 == 0 ? "Your integer ({0}) is even." : "Your integer ({0}) is odd.", number1);
Console.ReadKey();
}
}
// end main
}
// end Student challenge lab 2
There is something wrong with my code. I am teaching myself c# and one of the challenges in this chapter was to prompt the user for 10 numbers, store them in an array, than ask for 1 additional number. Then the program would say whether the additional number matched one of the numbers in the array. Now what I have below does work, but only if I enter in a comparison number that is less than 10 which is the size of the array.
I'm not sure how to fix it. I am not sure how to do the comparison. I tried a FOR loop first which kind of worked, but ran through the loop and displayed the comparison against all 10 numbers so you would get 9 lines of No! and 1 line of Yes!. I put in a break; which stopped it counting all 10 but if I entered the number 5 for comparison, then I would get 4 lines of No! and 1 of Yes!. The below has been the only way I could get it to work reliably but only as long as the number isn't out of the bounds of the array.
I can see why I get the error when the number is above 10, I just don't know what to use to compare it but still allow the user to enter in any valid integer. Any assistance would be great!
int[] myNum = new int[10];
Console.WriteLine("Starting program ...");
Console.WriteLine("Please enter 10 numbers.");
for (int i = 0; i <= 9; ++i)
{
Console.Write("Number {0}: ", i + 1);
myNum[i] = Int32.Parse(Console.ReadLine());
}
Console.WriteLine("Thank you. You entered the numbers ");
foreach (int i in myNum)
{
Console.Write("{0} ", i);
}
Console.WriteLine("");
Console.Write("Please enter 1 additional number: ");
int myChoice = Int32.Parse(Console.ReadLine());
Console.WriteLine("Thank you. You entered the number {0}.", myChoice);
int compareArray = myNum[myChoice - 1];
if (compareArray == myChoice)
{
Console.WriteLine("Yes! The number {0} is equal to one of the numbers you previously entered.", myChoice);
}
else
{
Console.WriteLine("No! The number {0} is not equal to any of the entered numbers.", myChoice);
}
Console.WriteLine("End program ...");
Console.ReadLine();
You were on the right track- you want to loop through the array in myNum and compare each element to the variable myChoice. If you don't want to print whether each element of the array is a match, create a new variable and use it to keep track of whether you've found a match or not. Then after the loop you can check that variable and print your finding. You'd usually use a bool variable for that- set it false to start, then true when you find a match.
bool foundMatch = false;
for (int i = 0; i < 10; i++) {
if (myNum[i] == myChoice) {
foundMatch = true;
}
}
if (foundMatch) {
Console.WriteLine("Yes! The number {0} is equal to one of the numbers you previously entered.", myChoice);
}
If you include the System.Linq namespace (or if you change the type of myNum to be something that implements ICollection<T>, like List<T>), you can use myNum.Contains(myChoice) to see if the value myChoice matches one of the values in myNum. array.Contains returns a boolean that is true if the specified value is found in the array and false if it is not.
You can update your code to use this like so:
//int compareArray = myNum[myChoice - 1]; // This line is no longer needed
if (myNum.Contains(myChoice))
{
Console.WriteLine("Yes! The number {0} is equal to one of the numbers you previously entered.", myChoice);
}
else
{
Console.WriteLine("No! The number {0} is not equal to any of the entered numbers.", myChoice);
}
If you're looking for numbers that are definitely between 1 and 10, then before you use
int compareArray = myNum[myChoice - 1];
check if it's over the value of 10. For example:
while(myChoice > 10)
{
Console.Write("Please choose a number less than or equal to 10: ");
myChoice = Int32.Parse(Console.ReadLine());
}
The benefit of putting it inside a while loop instead of an if tag means that, when the user enters another number, the value of myChoice will be rewritten, and compared against. If they enter a number over 10, it'll keep responding Please choose a number less than or equal to 10. until the number they input is below or equal to 10:` Then, your program will continue.
However, if you want to compare it against the array, rather than put in a fixed number comparison, consider the following while loop:
while(myChoice > myNum.Length)
{
Console.Write("Please choose a number less than or equal to {0}: ", myNum.Length);
myChoice = Int32.Parse(Console.ReadLine());
}
This will work for any sized array then, without you having to change the while loops content. By using this system, you can then ensure that you won't get an IndexOutOfBounds exception, so long as you subtract 1 when using it as an index.
You are looking to compare a final, 11th value and trying to determine if its in an array of 10 previous entries?
Try:
for(int i = 0; i < array.length - 1; i++;)
{
If(array[i] == input)
return true;
}
return false;
You should be able to figure out how to implement this completely yourself, as you did want to do it as an exercise.
Edit: If someone wants to check this or complete it in correct syntax, go ahead. I posted this rough outline from a phone.
public static void duel(String user, String user1, String user2)
{
int[] value = null;
String winner;
for (int i = 0; i < 2; i++)
{
Random rand = new Random((int)DateTime.Now.Ticks);
int numIterations = 0;
numIterations = rand.Next(2, 12);
value[i] = numIterations;//This is line 286
}
if (value[0] > value[1])
{
winner = user1;
}
else
{
winner = user2;
}
Console.WriteLine(user + " Started a duel against " + user1 + " and " + user2 + "!");
Console.WriteLine(user1 + " rolled " + value[0] + " and " + user2 + " rolled " + value[1] + "!");
Console.WriteLine(winner + " is the winner!");
}
What exactly is wrong here? When I set int[] value = null it compiles but if I remove the null it says Use of unassigned local variable 'value' Line 286
Well yes, you have to assign a value to the value variable before you use it - but when you've set it to null, you will get a NullReferenceException when you try to use it. It looks like you want a two element array, so use
int[] value = new int[2];
However, with the code you've written you'll almost certainly end up with the two values being the same, as you're creating two instances of Random at almost exactly the same time. See my article on Random for more information.
I would pass a Random instance into the method, and rewrite it like this - without the somewhat-pointless loop:
public static void Duel(Random rng, String user, String user1, String user2)
{
// Using Next(2, 12) doesn't really mimic 2 dice of 1-6; it actually mimics
// a single 10-sided die with values 2 to 11 inclusive.
int score1 = rng.Next(1, 7) + rng.Next(1, 7);
int score2 = rng.Next(1, 7) + rng.Next(1, 7);
// Note: this is biased in favour of user2 in case of equality
string winner = score1 > score2 ? user1 : user2;
Console.WriteLine("{0} started a duel between {0} and {1}!",
user, user1, user2);
Console.WriteLine("{0} rolled {1} and {2} rolled {3}!", user1, score1,
user2, score2);
Console.WriteLine("{0} is the winner!", winner);
}
Things to note here:
Our method depends on something which it can't necessarily create correctly itself (the Random) so that is injected.
Simulate rolling two dice (which is what I assume the aim is) by rolling two single dice, not picking a single number in the range [2, 12] uniformly.
The second parameter to Random.Next is an exclusive upper bound (I got that wrong until I was checking it over)
Use of the conditional operator when you want to pick one expression or another based on a condition, and do the same thing with the result either way
Use of composite format strings to make it easier to format strings than simple concatenation
Following .NET naming conventions (Duel, not duel)
Change the line to:
int[] value = new int[2];
You need to create an empty array so that you can use it later.
If you don't set it to anything you get the Use of unassigned local variable, because you've declared the variable, but haven't given it a value.
If you set it to null then that's giving it a value, but you're also not putting anything in that variable. Your code further down expects to be able to use elements 0 and 1, however although you declared that value is an array you've not created an array to put into the variable, so you get the error when trying to access the elements of a non-existent array.
The code above fixes this by setting the variable to an array with 2 element, which would contain the default for the type in the array (int), which in this case would be 0 until you set them equal to something.
Bad analogy time:
Imagine i'm planning on putting a bookshelf in my bedroom. I make space for it (declare the variable), but i don't put a bookshelf in that space (set the variable it to null, or don't set it at all).
If i go to get something on the 2nd shelf i'm obviously going to have a problem as although i've made space (a variable) in my room (my program) i've not put a bookshelf there (declared an array to go in the variable).
For more info, see the Arrays Tutorial on MSDN.
You are referencing value[i], but you haven't actually intialized value[] yet.
You need to do something like
value = new int[2];
You haven't assigned your int[] an instance. If you know there will always be 2 values, you can use:
int[] value = new int[2];
If you don't know that you'll only ever have 2 values, consider using a List:
List<int> value = new List<int>();
In c# you need to initialize your variables to some value or it will not compile. To fix your runtime error, you need to initialize value into an array (instead of null). Since you are looping through value twice I assume you need to do something like this:
int[] value = new int[2];
You need to create your array somewhere :
int[] value = new int[2];
If you just declare the array in the beginning you should be safe.
int[] value = new int[2];