My code works for the most part, I tried finding a solution online but struggled to find my exact issue. Here's the code, in C#:
static void Main(string[] args)
{
int maxFilm = 5;
int minFilm = 1;
Console.WriteLine("We are currently showing:");
Console.WriteLine("1. Rush");
Console.WriteLine("2. How I live now");
Console.WriteLine("3. Thor");
Console.WriteLine("4. Filth");
Console.WriteLine("5. Planes");
const int minAge1 = 15;
const int minAge2 = 12;
const int minAge3 = 18;
int filmNumber;
string filmNum;
int age;
string stringAge;
do
{
Console.WriteLine("Enter the number of the film you wish to see: ");
filmNum = Console.ReadLine();
filmNumber = Int32.Parse(filmNum);
if (filmNumber > maxFilm || filmNumber < minFilm)
{
Console.WriteLine("Invalid film number");
}
}
while (filmNumber > maxFilm || filmNumber < minFilm);
do
{
Console.WriteLine("Enter your age: ");
stringAge = Console.ReadLine();
age = Int32.Parse(stringAge);
if (age < 5 || age > 120)
{
Console.WriteLine("Invalid age");
}
} while (age < 5 || age > 120);
if (((filmNumber == 1 || filmNumber == 2) && age >= minAge1) || (filmNumber == 3 && age >= minAge2) || (filmNumber == 4 && age >= minAge3) || (filmNumber == 5))
{
Console.WriteLine("Enjoy the film");
}
else
{
Console.WriteLine("You are too young");
}
Input:
First, invalid movie number
Second, valid movie number
Third, age between 5-120
Expected output: Either "You are too young" or "enjoy the film" and then the code exits
What happens: The code exits and then re-executes from the start.
If I put a valid film number to start with, then it performs as expected. Any help is appreciated
After your final Console.WriteLine(), add a Console.ReadLine()
Example:
Console.WriteLine("Enjoy the film");
Console.ReadLine();
Also if you don't want the program to close after this, I suggest putting the program into a loop.
I assume that you want to see out put, so you can use following code :
Console.ReadLine();
or
Console.ReadKey();
To put entire code. generally, in loop is not good idea.
Related
Im totaly new to programming and trying to find a basic solution, im making a very simple game and im giving the person 2 options to do something, and if they choose neither 1 or 2 i want the tell them to choose again. But cant find a way to do it.
int antalspelare = 0;
int.TryParse(Console.ReadLine(), out antalspelare);
if(antalspelare == 1)
{
string spelareEtt = Console.ReadLine();
}
else if(antalspelare == 2)
{
string spelareEtt = Console.ReadLine();
string spelareTva = Console.ReadLine();
}
Keep on learning! You'll need loops to accomplish that. In particular here while loop will be useful that will keep running until the condition is false.
int antalspelare = 0
while(antalspelare < 1 || antalspelare > 2)
{
Console.WriteLine("Enter option (1 or 2):");
int.TryParse(Console.ReadLine(), out antalspelare);
if(antalspelare == 1)
{
string spelareEtt = Console.ReadLine();
}
else if(antalspelare == 2)
{
string spelareEtt = Console.ReadLine();
string spelareTva = Console.ReadLine();
}
}
At first antalspelare is 0, and so antalspelare < 1 || antalspelare > 2 is true, we start first iteration of the loop. It prints the message, asks to read number. If the number is 1 or 2, does the action, and on the next iteration antalspelare < 1 || antalspelare > 2 is false, the loop will terminate. However if it was something not 1 or 2, then the loop will continue to ask for new number
Further, you can dedicate the loop only for reading antalspelare, and only after the loop continue all the logic, like so:
int antalspelare = 0
while(antalspelare < 1 || antalspelare > 2)
{
Console.WriteLine("Enter option (1 or 2):");
int.TryParse(Console.ReadLine(), out antalspelare);
}
string spelareEtt, spelareTva;
if(antalspelare == 1)
{
spelareEtt = Console.ReadLine();
}
else if(antalspelare == 2)
{
spelareEtt = Console.ReadLine();
spelareTva = Console.ReadLine();
}
// You can use spelareEtt and spelareTva here and further
Is there any more "elegant" way to filter a number input for specific parameters?
Like here, I need to say different things if you're to high, to low or of the limits.
Would appreciate if you explain what you suggest. I'm like 2 weeks into programming.
//VARIABLES
int userNumber;//uN
int searchedNumber;//sN
//NUMBER WE'RE LOOKING FOR
searchedNumber = 87;
//TASK FOR "CUSTOMER"
Console.WriteLine("Type in a number between 1-100!");
//DO-WHILE, because it hast to run one either way
do
{
//READING OUT CONSOLE
string userNumberString = Console.ReadLine();
//CONVERTING STRING TO INT
userNumber = int.Parse(userNumberString);
//uN > THAN sN BUT <= 100
if (userNumber > searchedNumber && userNumber <= 100)
{
Console.WriteLine("To High! /n Try again.");
}
//uN < THAN sN BUT >= 1
else if (userNumber < searchedNumber && userNumber >= 1)
{
Console.WriteLine("To Low! /n Try again.");
}
//uN >= 101 AND uN <= 0
else if (userNumber >= 101 || userNumber <= 0)
{
Console.WriteLine("Between 1 and 100, Dummy!");
}
else
{
//IF NOTHING IS TRUE uN=sN
Console.WriteLine("JACKPOT!");
}
//LOOPING CONDITION
} while (userNumber != searchedNumber);
If this q is already answered somewhere, i'm sorry. English is not my native language and i struggled to even find the right search term.
I suggest extracting methods, please, do not cram everything into huge single routine:
public static int ReadInteger(string title) {
if (!string.ISNullOrWhiteSpace(title))
Console.WriteLine(title);
while (true) {
if (int.TryParse(Console.ReadLine(), out int result))
return result;
Console.WriteLine("This is not a valid integer! Try again.");
}
}
public static string FeedBack(int user, int actual) {
if (user < 0 || user > 100)
return "Between 1 and 100, Dummy!"
else if (user < actual)
return "Too Low! /n Try again.";
else if (user > actual)
return "Too High! /n Try again.";
else
return "JACKPOT!"
}
Then use these methods in a tiny loop:
int userNumber = 0;
int searchedNumber = 87;
do {
userNumber = ReadInteger("Type in a number between 1-100!");
Console.WriteLine(FeedBack(userNumber, actual));
}
while (userNumber != searchedNumber);
One way to get rid of all the else statements is to move the code to a method and return from the method as soon as you know what the response should be.
Something like this
public string EvaluateNumber(int userNumber, int searchedNumber)
{
if (searchedNumber <= 0 || searchedNumber >= 101)
return "Between 1 and 100, Dummy!";
if (searchedNumber < userNumber)
return "Too low! /n Try again.";
if (searchedNumber > userNumber)
return "Too high! /n Try again.";
return "JACKPOT!"; // If we get to here, the numbers are equal
}
This code can get little bit cleaner by rearramging conditions - if will get a lot simplier :) Also, if you have one line under if, you can omit curly braces, see below code. I also included some comments, which I hope, wil be useful:
do
{
//READING OUT CONSOLE
string userNumberString = Console.ReadLine();
//CONVERTING STRING TO INT
// here you need to be careful, what if user types "a"?
// I suggest reading about int.TryParse :)
userNumber = int.Parse(userNumberString);
//uN >= 101 AND uN <= 0
if (userNumber >= 101 || userNumber <= 0)
Console.WriteLine("Between 1 and 100, Dummy!");
// now we are sure we are in the range
if (userNumber > searchedNumber)
Console.WriteLine("To High! /n Try again.");
else if (userNumber < searchedNumber)
Console.WriteLine("To Low! /n Try again.");
else
//IF NOTHING IS TRUE uN=sN
Console.WriteLine("JACKPOT!");
//LOOPING CONDITION
} while (userNumber != searchedNumber);
Thinking of a cleaner code:
public static void Main()
{
//VARIABLES
int userNumber;//uN
int searchedNumber = 87;
int min = 1;
int max = 100;
//TASK FOR "CUSTOMER"
Console.WriteLine($"Type in a number between {min}-{max}!");
//DO-WHILE, because it hast to run one either way
do
{
//READING OUT CONSOLE
string userNumberString = Console.ReadLine();
//CONVERTING STRING TO INT
if (int.TryParse(userNumberString, out userNumber))
{
if (userNumber >= min && userNumber <= max)
{
if (userNumber == searchedNumber)
{
Console.WriteLine("JACKPOT!");
}
else
{
Console.WriteLine("To " + (userNumber < searchedNumber ? "Low" : "High") + "! Try again.");
}
}
else
{
Console.WriteLine($"Between {min} and {max}, Dummy!");
}
}
else
{
Console.WriteLine($"One integer number, Dummy!");
}
} while (userNumber != searchedNumber);
}
The TryParse it's very important
So I made a basic game for a school assignment. One of the requirements is, to let program choose who is playing first, either the computer or the player. So I wrote an if/else statement then put my code inside of it. The code works, but then I added code which limits what numbers the player can input. Those numbers range from 1-3. If a players inputs a number less than one or greater than three they get an error message. After my if/else executed which picks the player who goes first, it stops working and only picks the player and not the computer. Is there a way to fix this?
int chips = 21, user, computer;
int pickPlayer;
Random rn = new Random();
pickPlayer = rn.Next(1, 5);
if (pickPlayer == 1 || pickPlayer == 2 || pickPlayer == 3 )
{
//Player goes First
while (chips > 0)
{
Console.WriteLine("There are {0} Chips Choose Either 1,2,3 chips", chips);
user = Convert.ToInt32(Console.ReadLine());
if (user > 3 || user <= 0)
{
Console.WriteLine("You can only take between 1 and 3 chips. Try again");
}
else
{
chips = chips - user;
Random rnd = new Random();
/*if (chips <= 0)
{
Console.WriteLine("You Lose");
Console.ReadLine();
} */
}
if (chips <= 0)
{
Console.WriteLine("You Lose");
Console.ReadLine();
}
}
}
else
{
//Computer goes first
while (chips > 0)
{
Console.WriteLine("There are {0} Chips Choose Either 1,2,3 or 4 chips", chips);
Random rnd = new Random();
computer = rnd.Next(1, 4);
user = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("Computer picks {0} chips", computer);
chips = chips - computer;
if (chips <= 0)
{
Console.WriteLine("You Lose");
Console.ReadLine();
}
else
{
if (user > 3 || user <= 0)
{
Console.WriteLine("You can only take between 1 and 3 chips. Try again");
}
else
{
chips = chips - user;
/*if (chips <= 0)
{
Console.WriteLine("You Win");
Console.ReadLine();
} */
}
if (chips <= 0)
{
Console.WriteLine("You Win");
Console.ReadLine();
}
}
}
}
Try this.
I corrected the algorithm and I refactored the code using anonymous methods and changing names but you can create class methods instead.
I used int.TryParse instead of Convert so it returns only a number or 0 in case of error.
Random random = new Random();
int chipsStart = 21;
int chipsCurrent = chipsStart;
int playerTake;
int computerTake;
bool playerFirst = random.Next(0, 2) == 0;
Func<bool> processPlayer = () =>
{
Console.WriteLine("There are {0} Chips Choose Either 1,2,3 chips", chipsCurrent);
do
{
int.TryParse(Console.ReadLine(), out playerTake);
}
while ( playerTake == 0 );
if ( playerTake < 1 || playerTake > 3 )
Console.WriteLine("You can only take between 1 and 3 chips. Try again");
else
chipsCurrent = chipsCurrent - playerTake;
if ( chipsCurrent > 0 )
return true;
else
{
Console.WriteLine("You Lose");
return false;
}
};
Func<bool> processComputer = () =>
{
computerTake = random.Next(1, 4);
Console.WriteLine("Computer picks {0} chips", computerTake);
chipsCurrent = chipsCurrent - computerTake;
if ( chipsCurrent > 0 )
return true;
else
{
Console.WriteLine("You Win");
return false;
}
};
if ( playerFirst )
while ( true )
{
if ( !processPlayer() ) break;
if ( !processComputer() ) break;
}
else
while ( true )
{
if ( !processPlayer() ) break;
if ( !processComputer() ) break;
}
Console.ReadLine();
I have a question, how to set the condition that if the user presses "Enter" when guessing a number, the program would ask "Enter a number"!
Program randomNumberA = new Program();
int r = randomNumberA.RandomNumber();
do
{
Console.WriteLine("Take a guess.\n");
string n = userNumberA.UserNumber();
int num;
int.TryParse(n, out num);
ConsoleKeyInfo key = Console.ReadKey();
if (IsAllDigits(n))
{
if (num > r)
{
Console.WriteLine("Your guess is too high!\n");
userGuess++;
}
if (num < r)
{
Console.WriteLine("Your guess is too low!\n");
userGuess++;
}
if (num == r)
{
Console.WriteLine($"Good job, {name}! You guessed my number in {userGuess} guesses!");
break;
}
}
else if (!IsAllDigits(n) || string.IsNullOrEmpty(n) || !char.IsNumber(key.KeyChar))
{
Console.WriteLine("Please enter the correct number!");
continue;
}
} while (userGuess <= USER_LIMIT);
if (userGuess > USER_LIMIT)
{
Console.WriteLine("Game Over!");
}
This logic checks the game, but still does not work if the user presses the "Enter" button
The code you've posted is slightly incomplete, but you're comparing the result of userNumberA.UserNumber() to r and not using key until the very last else if condition, which is confusing.
I think your logic can be changed slightly. Here is a sample with some hard-coded values that you should be able to leverage in your existing code:
private static Random _random = new Random();
static void Main(string[] args)
{
// Pick a random number between 1 and 100 for the user to guess
int secretNumber = _random.Next(1, 101);
int USER_LIMIT = 3;
int userGuess = 0;
Console.Write("Please enter your name: ");
string name = Console.ReadLine();
while (userGuess < USER_LIMIT)
{
userGuess++;
Console.Write("Guess a number between 1 and 100: ");
int num;
if (int.TryParse(Console.ReadLine(), out num))
{
if (num > secretNumber)
{
Console.WriteLine("Your guess is too high!\n");
}
else if (num < secretNumber)
{
Console.WriteLine("Your guess is too low!\n");
}
else
{
Console.WriteLine($"\nGood job, {name}! That only took {userGuess} guesses!");
break;
}
}
else
{
Console.WriteLine("Please enter a valid number!");
}
}
Console.WriteLine("\nGame Over!");
if (userGuess == USER_LIMIT) Console.WriteLine($"\nThe number was: {secretNumber}");
GetKeyFromUser("\nDone! Press any key to exit...");
}
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 5 years ago.
Improve this question
The Following :
if (parseok == false)
{
Console.WriteLine("Error : Please enter valid numeric Value ");
Console.ReadLine();
Environment.Exit(0);
}
//Is currently working fine, however, I am wanting to change the if statement to a while loop - for error checking purposes. When I change the code to this :
while (parseok == false)
{
Console.WriteLine("Error : Please enter valid numeric Value ");
Console.ReadLine();
Console.Write("Please enter minutes for your first run: ");
parseok = int.TryParse(Console.ReadLine(), out run1m);
}
//I am recieveing an error message saying that I'm missing a close bracket, when I add the close bracket the whole program becomes riddled with errors. What am I forgetting to do?
//I will add the entire project's code :
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApp1
{
class Program
{
//Ajdin Karahodzic
//ID : KARAD1301
static void Main(string[] args)
{
String membertype = "";
//Declaration of Variables
string name = "";
string member = "";
string gender = "";
int run1m = 0;
int run1s = 0;
int run2m = 0;
int run2s = 0;
int run3m = 0;
int run3s = 0;
int run1total = 0;
int run2total = 0;
int run3total = 0;
int totalsecs = 0;
int avgsecs = 0;
int hours = 0;
int minutes = 0;
int seconds = 0;
bool parseok = false;
string menu = "";
int run1tempS = 0;
int run1tempM = 0;
int run1tempH = 0;
int run2tempS = 0;
int run2tempM = 0;
int run2tempH = 0;
int run3tempS = 0;
int run3tempM = 0;
int run3tempH = 0;
while (menu != "x")
{
Console.WriteLine("Please choose from the following : ");
Console.WriteLine("Enter Runner Details (R) : ");
Console.WriteLine("Enter run times (T) : ");
Console.WriteLine("Display runner results (D) : ");
Console.WriteLine("Exit the program (X) ");
menu = Console.ReadLine();
switch (menu)
{
//CLOSE PROGRAM SWITCH
case "x":
case "X":
Environment.Exit(0);
break;
//ENTER RUNNER DATA SWITCH
case "r":
case "R":
Console.Write("Please enter your name: ");
name = Console.ReadLine();
while (string.IsNullOrEmpty(name))
{
Console.WriteLine("Error : Please ensure you have entered your name, press enter to continue ");
Console.ReadLine();
Console.Write("Please enter your name: ");
name = Console.ReadLine();
}
Console.Write("Please enter your membership number: ");
member = Console.ReadLine();
while (member.Length != 5)
{
Console.WriteLine("Error : Membership number must be 5 characters long, press enter to continue ");
Console.ReadLine();
Console.Write("Please enter your membership number: ");
member = Console.ReadLine();
}
char first = member[0];
while (first != 'o' && first != 'O' && first != 's' && first != 'S' && first != 'j' && first != 'J' && first != 'C' && first != 'c')
{
Console.WriteLine("Error : Membership number must begin with O, S, J or C, press enter to continue ");
Console.ReadLine();
Console.Write("Please enter your membership number: ");
member = Console.ReadLine();
}
if (first == 'o' || first == 'O')
{
membertype = "Ordinary Member";
}
else if (first == 's' || first == 'S')
{
membertype = "Student Member";
}
else if (first == 'j' || first == 'J')
{
membertype = "Junior Member";
}
else if (first == 'c' || first == 'C')
{
membertype = "Child Member";
}
string response = "";
Console.Write("Please enter your gender (m) or (f) : ");
response = Console.ReadLine();
gender = response;
while (gender != "m" && gender != "M" && gender != "f" && gender != "F")
{
Console.WriteLine("Error : Gender must be either : M / m (For Male) or F / f (For Female), press enter to continues ");
Console.ReadLine();
Console.Write("Please enter your gender (m) or (f) : ");
response = Console.ReadLine();
gender = response;
}
break;
//ENTER RUN TIMES - SWITCH
case "T":
case "t":
//Prompt for user input; collect and store data.
/*---------RUN 1 INPUT---------
-----------------------------*/
//MINUTES
Console.Write("Please enter minutes for your first run: ");
parseok = int.TryParse(Console.ReadLine(), out run1m);
while (parseok == false)
{
Console.WriteLine("Error : Please enter valid numeric Value ");
Console.ReadLine();
Console.Write("Please enter minutes for your first run: ");
parseok = int.TryParse(Console.ReadLine(), out run1m);
}
else if (run1m < 15 || run1m > 180)
{
Console.WriteLine("Error : Minutes cannot be less than 15 or greater than 180");
Console.ReadLine();
Environment.Exit(0);
}
//SECONDS
Console.Write("Please enter seconds for your first run: ");
parseok = int.TryParse(Console.ReadLine(), out run1s);
if (parseok == false)
{
Console.WriteLine("Error : Please enter valid numeric Value ");
Console.ReadLine();
Environment.Exit(0);
}
else if (run1s < 0 || run1s > 59)
{
Console.WriteLine("Error : Seconds must be between 0 and 59 ");
Console.ReadLine();
Environment.Exit(0);
}
Console.WriteLine();
/*---------RUN 2 INPUT---------
------------------------------*/
Console.Write("Please enter minutes for your second run: ");
parseok = int.TryParse(Console.ReadLine(), out run2m);
if (parseok == false)
{
Console.WriteLine("Error : Please enter valid numeric Value ");
Console.ReadLine();
Environment.Exit(0);
}
else if (run2m < 15 || run2m > 180)
{
Console.WriteLine("Error : Minutes cannot be less than 15 or greater than 180");
Console.ReadLine();
Environment.Exit(0);
}
Console.Write("Please enter seconds for your second run: ");
run2s = int.Parse(Console.ReadLine());
if (parseok == false)
{
Console.WriteLine("Error : Please enter valid numeric Value ");
Console.ReadLine();
Environment.Exit(0);
}
else if (run2s < 0 || run2s > 59)
{
Console.WriteLine("Error : Seconds must be between 0 and 59 ");
Console.ReadLine();
Environment.Exit(0);
}
Console.WriteLine();
/*---------RUN 3 INPUT---------
------------------------------*/
Console.Write("Please enter minutes for your third run: ");
parseok = int.TryParse(Console.ReadLine(), out run3m);
if (parseok == false)
{
Console.WriteLine("Error : Please enter valid numeric Value ");
Console.ReadLine();
Environment.Exit(0);
}
else if (run3m < 15 || run3m > 180)
{
Console.WriteLine("Error : Minutes cannot be less than 15 or greater than 180");
Console.ReadLine();
Environment.Exit(0);
}
Console.Write("Please enter seconds for your third run: ");
run3s = int.Parse(Console.ReadLine());
if (parseok == false)
{
Console.WriteLine("Error : Please enter valid numeric Value ");
Console.ReadLine();
Environment.Exit(0);
}
else if (run3s < 0 || run3s > 59)
{
Console.WriteLine("Error : Seconds must be between 0 and 59 ");
Console.ReadLine();
Environment.Exit(0);
}
Console.WriteLine();
break;
case "d":
case "D":
// CALCULATIONS
//Converting individual run times to seconds
run1total = (run1m * 60) + run1s;
run2total = (run2m * 60) + run2s;
run3total = (run3m * 60) + run3s;
//Convert individual times to hours, mins, secs.
// RUN1
run1tempS = (run1total % 60);
run1tempM = ((run1total / 60) % 60);
run1tempH = ((run1total / 3600) % 60);
// RUN2
run2tempS = (run2total % 60);
run2tempM = ((run2total / 60) % 60);
run2tempH = ((run2total / 3600) % 60);
// RUN3
run3tempS = (run3total % 60);
run3tempM = ((run3total / 60) % 60);
run3tempH = ((run3total / 3600) % 60);
//Calculate average time
totalsecs = (run1total + run2total + run3total);
avgsecs = (totalsecs / 3);
seconds = (avgsecs % 60);
minutes = ((avgsecs / 60) % 60);
hours = ((avgsecs / 3600) % 60);
//Display results
Console.WriteLine();
Console.WriteLine("==========================================================================");
Console.WriteLine("10 Km results for: ");
Console.WriteLine("{0} [{1}] - {2}, {3} ", name, member, membertype, gender.ToUpper());
Console.WriteLine("Run 1 - {0} hr(s) {1} min(s) {2} sec(s). ", run1tempH, run1tempM, run1tempS);
Console.WriteLine("Run 2 - {0} hr(s) {1} min(s) {2} sec(s). ", run2tempH, run2tempM, run2tempS);
Console.WriteLine("Run 3 - {0} hr(s) {1} min(s) {2} sec(s). ", run3tempH, run3tempM, run3tempS);
Console.WriteLine();
Console.WriteLine("Average 10km run time is : {0} hours {1} minutes {2} seconds. ", hours, minutes, seconds);
break;
default:
Console.WriteLine("Incorrect input, please try again ");
break;
}
Console.ReadLine();
}
}
}
}
On line 161 you are doing an else if but there fore you did'nt specify any if.
I don't know what your doing in your code. But either remove the else in the else if statement or create an if statement before the else if.
An else if statement comes after an if statement or else if statement and can not be the first one in a comparison.
Solution example
So by adding an if before else if will solve the problem. (Notice I don't now what your program needs to do so you need to check what condition check you have to do.)
Your problem is the left over
else
on line 163. Removing that allows the code to compile, but I'm not going to verify the behaviour.