Input Issues when using do-while loop - c#

Whenever input is outside of range 1-4 its supposed to throw an Invalid entry text and ask for another input, however when you type in another input, the program error's out and doesn't continue. I'm not sure where I am going wrong. I am using C# and this is an assignment that requires me to use the do while loop for this section.
static void Main(string[] args)
{
Write("Enter a salespersons name: ");
string salesPerson = ReadLine();
int intItem;
int intQuantity;
double item1 = 239.99;
double item2 = 129.75;
double item3 = 99.95;
double item4 = 350.89;
double dblItemSales;
double dblTotalSales;
do
{
Write("Enter an item number between 1 and 4 or -1 to quit: ");
intItem = Convert.ToInt32(ReadLine());
if ( intItem < 1 || intItem > 4 )
{
WriteLine("Invalid Entry");
Write("Enter an item number between 1 and 4 or -1 to quit: ");
intItem = Convert.ToInt32(ReadLine());
}
else if ( intItem == -1 )
{
WriteLine("Salesperson " + salesPerson + " sold a total of ");
break;
}
else
Write("Enter the quantity sold: ");
intQuantity = Convert.ToInt32(ReadLine());
}
while ( intItem != -1 );
WriteLine("Press Enter to Continue.");
ReadLine();
}

static void Main(string[] args)
{
Write("Enter a salespersons name: ");
string salesPerson = ReadLine();
int intItem;
int intQuantity;
double item1 = 239.99;
double item2 = 129.75;
double item3 = 99.95;
double item4 = 350.89;
double dblItemSales;
double dblTotalSales;
do
{
Write("Enter an item number between 1 and 4 or -1 to quit: ");
if (Int32.TryParse(ReadLine(), out intItem))
{
if (intItem == -1)
{
WriteLine("Salesperson " + salesPerson + " sold a total of ");
break;
}
else if (intItem < 1 || intItem > 4)
{
WriteLine("Invalid Entry");
}
else
{
Write("Enter the quantity sold: ");
if (!Int32.TryParse(ReadLine(), out intQuantity))
{
intQuantity = 0; // or whatever
}
}
}
}
while (intItem != -1);
WriteLine("Press Enter to Continue.");
ReadLine();
}

Since -1 < 1 it is the very first branch
if ( intItem < 1 || intItem > 4 ) // true when intItem == -1
{
...
}
else if ( intItem == -1 ) // this branch will never be executed
which runs. Put it like this:
while (true) { // keep looping until explicit quit
Write("Enter an item number between 1 and 4 or -1 to quit: ");
if (!int.TryParse(ReadLine(), out var intItem)) // what if user put "bla-bla-bla"?
Write("Syntax error. Integer 1..4 expected");
else if (intItem == -1) { // quit
WriteLine("Salesperson " + salesPerson + " sold a total of ");
break;
}
else if (intItem < 1 || intItem > 4) { // invalid range
WriteLine("Invalid Entry");
Write("Enter an item number between 1 and 4 or -1 to quit:");
}
else { // main routine
// intItem is integer in 1..4 range
Write("Enter the quantity sold: ");
//TODO: put relevant code here
}
}

You can try such thing, depending of what you want to do with quantities entered hence I put something for the sample:
bool isValid;
do
{
Console.Write("Enter an item number between 1 and 4 or -1 to end: ");
int.TryParse(Console.ReadLine(), out intItem);
if ( intItem == -1 ) break;
if ( intItem < 1 || intItem > 4 )
{
Console.WriteLine("Invalid entry: try again, please.");
continue;
}
dblItemSales++;
do
{
Console.Write("Enter the quantity sold: ");
isValid = int.TryParse(Console.ReadLine(), out intQuantity) && intQuantity >= 0;
if ( !isValid )
Console.WriteLine("Invalid entry: try again, please.");
}
while ( !isValid );
dblTotalSales += intQuantity;
}
while ( true );
Console.WriteLine($"Sales person {salesPerson} sold a total of {dblTotalSales}" +
$" for {dblItemSales} items");
Console.WriteLine("Press Enter to Continue.");
We use TryParse to ensure that a number is entered else it is 0 and the method rertuens false.

In case you don't want to change the current code. Short fix:
Move this intQuantity = Convert.ToInt32(Console.ReadLine()); line inside the else statement.
Delete this codes inside if statement:
Write("Enter an item number between 1 and 4 or -1 to quit: ");
intItem = Convert.ToInt32(ReadLine());
It should be look like this:
do
{
Console.Write("Enter an item number between 1 and 4 or -1 to quit:");
intItem = Convert.ToInt32(Console.ReadLine());
if (intItem< 1 || intItem> 4)
{
Console.WriteLine("Invalid Entry");
}
else if (intItem == -1)
{
Console.WriteLine("Salesperson " + salesPerson + " sold a total of ");
break;
}
else
{
Console.Write("Enter the quantity sold: ");
intQuantity = Convert.ToInt32(Console.ReadLine());
}
}
while (intItem != -1);
Console.WriteLine("Press Enter to Continue.");
Console.ReadLine();

Related

My If/else statement is not executing properly

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();

How to put Pin in 4 digits only when entering a PIN and how to verified it?

I don't know the codes as I'm a beginner in c#, so could anyone help me with these? I want my pin to enter in 4 digits only and re verified the pin to continue in the menu?
{
class program
{
public static void Main()
{
int amount = 1000, deposit, withdraw;
int choice, pin = 0, x = 0;
Console.WriteLine("Enter Your Pin Number ");
pin = int.Parse(Console.ReadLine());
while (true)
{
Console.WriteLine("********Welcome to ATM Service**************\n");
Console.WriteLine("1. Check Balance\n");
Console.WriteLine("2. Withdraw Cash\n");
Console.WriteLine("3. Deposit Cash\n");
Console.WriteLine("4. Quit\n");
Console.WriteLine("*********************************************\n\n");
Console.WriteLine("Enter your choice: ");
choice = int.Parse(Console.ReadLine());
switch (choice)
{
case 1:
Console.WriteLine("\n YOUR BALANCE IN Rs : {0} ", amount);
break;
case 2:
Console.WriteLine("\n ENTER THE AMOUNT TO WITHDRAW: ");
withdraw = int.Parse(Console.ReadLine());
if (withdraw % 100 != 0)
{
Console.WriteLine("\n PLEASE ENTER THE AMOUNT IN MULTIPLES OF 100");
}
else if (withdraw > (amount - 500))
{
Console.WriteLine("\n INSUFFICENT BALANCE");
}
else
{
amount = amount - withdraw;
Console.WriteLine("\n\n PLEASE COLLECT CASH");
Console.WriteLine("\n YOUR CURRENT BALANCE IS {0}", amount);
}
break;
case 3:
Console.WriteLine("\n ENTER THE AMOUNT TO DEPOSIT");
deposit = int.Parse(Console.ReadLine());
amount = amount + deposit;
Console.WriteLine("YOUR BALANCE IS {0}", amount);
break;
case 4:
Console.WriteLine("\n THANK U USING ATM");
break;
}
}
Console.WriteLine("\n\n THANKS FOR USING OUT ATM SERVICE");
}
}
}
I suggest something like this:
// read size (4) digits
private static string ReadPin(int size = 4) {
StringBuilder sb = new StringBuilder(size);
while (sb.Length < size) {
var key = Console.ReadKey(true); // we don't want to show the secret pin on the screen
// Uncomment, if you want to let user escape entering the PIN
// if (key.Key == ConsoleKey.Escape) {
// return "";
// }
if (key.KeyChar >= '0' && key.KeyChar <= '9') {
sb.Append(key.KeyChar);
Console.Write('*'); // let's show * instead of actual digit
}
}
return sb.ToString();
}
...
// private: there's no need for Main to be public
private static void Main() {
...
Console.WriteLine("Enter Your Pin Number ");
int pin = int.Parse(ReadPin());
If you want to verify the given string (pin) which is expected to be of length size, you can try either Linq
using System.Linq;
...
string pin = ...
int size = 4;
bool isValidPin = pin.Length == size && pin.All(c => c >= '0' && c <= '9');
Or regular expressions:
using System.Text.RegularExpressions;
...
bool isValidPin = Regex.IsMatch(pin, $"^[0-9]{{{size}}}$");
int password;
int repassword
Do{
Console.WriteLine("\n Enter the password");
password= int.Parse(Console.ReadLine()); //first password
string ps = Convert.ToString(password);
}while(ps.Length!=4) //request the password if is not composed by 4 digits
//menu part//
Do{
Console.WriteLine("\n Reinsert the password");
repassword= int.Parse(Console.ReadLine()); //reinsert password
} while(repassword!=password)

C# Blocking specific types of answers using a sentinel value

I am writing a code to get the highest mark and lowest mark. It also collects the average. It uses 999 to exit out of the do loop.
I need to get it to stop adding the invalid answers as well as the 999, but I can't get it to work.
(mark != 999) stops 999, the exit command, from being added to the grades we're trying to track, but I need to make it so it blocks marks above 100 or below 0 and I can't seem to get it to work.
The block of code I am working with is this:
if (mark != 999 && (mark < 0 || mark > 100))
{
sum += mark;
count++;
}
This is the main program:
int mark,
sum = 0,
lowMark = 100,
highMark = 0,
average,
count = 0;
char playagain = 'N';
// In a do loop, ask the user to enter a grade for a student or 999 to quit
do
{
do
{
Console.Write("Please enter a mark for the student or enter 999 to quit: ");
mark = int.Parse(Console.ReadLine());
while (mark != 999)
{
if (mark != 999 && (mark < 0 || mark > 100))
{
sum += mark;
count++;
}
if (mark < lowMark)
{
lowMark = mark;
}
if (mark > highMark)
{
highMark = mark;
}
if (mark < 0 || mark > 100)
{
Console.WriteLine("Invalid input value.");
Console.Write("Please enter a mark for the student or enter 999 to quit: ");
mark = int.Parse(Console.ReadLine());
}
else break;
}
} while (mark != 999);
average = sum / count;
Console.WriteLine($"\nThe class average was {average}%");
Console.WriteLine($"The highest mark was {highMark}% and the lowest mark was {lowMark}%");
Console.WriteLine("\nWould you like to start again?: Y/N");
playagain = char.Parse(Console.ReadLine());
playagain = char.ToUpper(playagain);
} while (playagain == 'Y');
// In a while loop, the program will:
// - Determine if the entered mark is the highest or lowest grade
// - Validate the entered grade before entering another grade; display some error
// message if the grade is invalid (i.e. < 0 or > 100)
// - Prompt the user to enter another grade or 999 to quit
// If there are valid marks:
// - Calculate the average grade for the class
// - Display the average, highest, and lowest grades
// Else, display some error message
// - Prompt the user to redo the steps above or quit.
As it is pointed out in the comments, this line
if (mark != 999 && (mark < 0 || mark > 100))
only evaluates to true when you input a mark less than 0 or greater than 100, which contradicts your requirement. So the condition should be written like
if (mark >= 0 && mark <= 100)
And for the while loops, the point is deciding when to break or continue. A good practice is checking conditions at the start, if certain conditions are met like user inputting 999 or invalid mark, break or continue immediately without going further.
So for the inner while loop, you can write it like this
while (true)
{
Console.Write("Please enter a mark for the student or enter 999 to quit: ");
mark = int.Parse(Console.ReadLine());
if (mark == 999) //get signal for exit
{
break; //go no further, stop the loop
}
if (mark < 0 || mark > 100) //invalid inputs
{
Console.WriteLine("Invalid input value.");
Console.Write("Please enter a mark for the student or enter 999 to quit: ");
continue; //go no further, continue the loop, let user input again
}
//handle valid inputs
sum += mark;
count++;
if (mark < lowMark)
{
lowMark = mark;
}
if (mark > highMark)
{
highMark = mark;
}
}
Try this.
class Program
{
static void Main(string[] args)
{
bool playAgain = true;
while (playAgain)
{
decimal mark = 0, lowMark = -1, highMark = -1, sum = 0, average = 0;
int count = 0;
do
{
Console.Write("Please enter a mark for the student or enter 999 to quit: ");
if (!decimal.TryParse(Console.ReadLine(), out mark) ||
(mark < 0 || mark > 100 || (mark > 0 && mark < 1)))
{
Console.WriteLine("Invalid input value.");
continue;
}
else
{
mark = mark / (decimal)100;
sum += mark;
count++;
if (lowMark < 0 || mark < lowMark)
{
lowMark = mark;
}
if (mark > highMark)
{
highMark = mark;
}
}
} while (mark != 999);
average = count == 0 ? 0 : sum / count;
lowMark = lowMark < 0 ? 0 : lowMark;
highMark = highMark < 0 ? 0 : highMark;
Console.WriteLine("\nThe class average was {0}",
average.ToString("P1", CultureInfo.InvariantCulture));
Console.WriteLine("The highest mark was {0} and the lowest mark was {1}",
highMark.ToString("P1", CultureInfo.InvariantCulture),
lowMark.ToString("P1", CultureInfo.InvariantCulture));
Console.WriteLine("\nWould you like to start again?: Y/N");
playAgain = Console.ReadKey().Key == ConsoleKey.Y;
Console.WriteLine();
}
}
}

Extra brackets expected? [closed]

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.

Invalid expression term 'else' after i typed it the second time

static void Main(string[] args)
{
Console.WriteLine("what is the value of 3 + 8?");
number = int.Parse(Console.ReadLine());
if (number == 11)
{
Console.WriteLine("well done");
Console.WriteLine("press enter once");
Console.ReadLine();
}
else;
{
Console.WriteLine("its 11 u idiot!!!");
Console.ReadLine();
}
Console.WriteLine("what is the value of 23132-23131?");
number = int.Parse(Console.ReadLine());
if (number == 1);
{
Console.WriteLine("oh yeah!");
Console.ReadLine();
}
else;
{
Console.WriteLine("u r such a noob!");
Console.ReadLine();
}
}
What is the problem there??? Visual studio told me invalid expression term 'else' after the second 'else' i typed and i don't know why?
Remove the semicolon after each of the two else keywords:
else // was else;
and after the if line:
if (number == 1) // was if (number == 1);
In addition, you should actually declare number:
var number = int.Parse(Console.ReadLine());
This is the final version of code that should work:
static void Main(string[] args)
{
Console.WriteLine("what is the value of 3 + 8?");
var number = int.Parse(Console.ReadLine());
if (number == 11)
{
Console.WriteLine("well done");
Console.WriteLine("press enter once");
Console.ReadLine();
}
else
{
Console.WriteLine("its 11 u idiot!!!");
Console.ReadLine();
}
Console.WriteLine("what is the value of 23132-23131?");
number = int.Parse(Console.ReadLine());
if (number == 1)
{
Console.WriteLine("oh yeah!");
Console.ReadLine();
}
else
{
Console.WriteLine("u r such a noob!");
Console.ReadLine();
}
}
Do it like this
int number;
Console.WriteLine("what is the value of 3 + 8?");
number = int.Parse(Console.ReadLine());
if (number == 11)
{
Console.WriteLine("well done");
Console.WriteLine("press enter once");
Console.ReadLine();
}
else
{
Console.WriteLine("its 11 u idiot!!!");
Console.ReadLine();
}
Console.WriteLine("what is the value of 23132-23131?");
number = int.Parse(Console.ReadLine());
if (number == 1)
{
Console.WriteLine("oh yeah!");
Console.ReadLine();
}
else
{
Console.WriteLine("u r such a noob!");
Console.ReadLine();
}

Categories