Adding an error message before restarting loop in c# - c#

I am trying to add an error message that says "Please enter a non-zero or non-negative number" before my loop asks the user for input again. Here is what I have right now. Any text I try seems to only appear when the user inputs the correct number. Here is what I have right now.
using System;
public class Program
{
public static void Main()
{
double length;
bool isInteger = false;
do
{
Console.WriteLine("Please Enter Length: ");
isInteger = double.TryParse(Console.ReadLine(), out length);
}
while (!(isInteger && length >= 0));
Console.WriteLine();
Console.WriteLine("You have input: " + length);
Console.WriteLine();
{
double width;
bool isInteger2 = false;
do
{
Console.WriteLine("Please Enter Width: ");
isInteger2 = double.TryParse(Console.ReadLine(), out width);
}
while (!(isInteger2 && width >= 0));
Console.WriteLine();
Console.WriteLine("You have input: " + width);
Console.WriteLine();
{
double height;
bool isInteger3 = false;
do
{
Console.WriteLine("Please Enter Height: ");
isInteger3 = double.TryParse(Console.ReadLine(), out height);
}
while (!(isInteger3 && height >= 0));
Console.WriteLine();
Console.WriteLine("You have input " + height);
Console.WriteLine();
}
}
}
}

You can use a pattern like this:
double length;
bool success;
do
{
Console.WriteLine("Please Enter Length: ");
success = double.TryParse(Console.ReadLine(), out length) && (length > 0);
if (!success)
{
Console.WriteLine("Please enter a non-zero or non-negative number");
}
}
while (!success);

If open to using a open source NuGet package Spectre.Console
internal partial class Program
{
static void Main(string[] args)
{
double length = GetDouble("Please Enter Length:");
double width = GetDouble("Please Enter Width:");
double height = GetDouble("Please Enter Height:");
Console.WriteLine();
Console.WriteLine($"Length {length} Width {width} Height {height}");
Console.ReadLine();
}
public static double GetDouble(string title) =>
AnsiConsole.Prompt(
new TextPrompt<double>(title)
.PromptStyle("white")
.Validate(input => input switch
{
< 1 => ValidationResult.Error("[cyan]1 is min value[/]"),
_ => ValidationResult.Success(),
}));
}

Related

Restarting a program after error in catch statement

I'm trying to restart my program after I catch an error using the catch() function, but I also want it to display the error, stop the rest of the program from running, and restart the program.
This is just a shortened version of my code which I have used as an example.
using System;
namespace Calculator
{
internal class Program
{
private static void Main(string[] args)
{
float input = 0;
while (input != 5)
{
Console.Clear();
Console.WriteLine("What would you like to do? Type: 1 for Addition. Write 5 to end program.");
try
{
input = float.Parse(Console.ReadLine());
}
catch (FormatException)
{
Console.WriteLine("Please enter a number");
}
//Addition
if (input == 1)
{
Console.WriteLine("Enter First Value: ");
string FirstValue = Console.ReadLine();
float firstval = 0;
try
{
firstval = float.Parse(FirstValue);
}
catch (FormatException)
{
Console.WriteLine("Please enter a number");
break;
}
Console.WriteLine("Enter Second Value: ");
string SecondValue = Console.ReadLine();
float secval = 0;
try
{
secval = float.Parse(SecondValue);
}
catch (FormatException)
{
Console.WriteLine("Please enter a number");
break;
}
float sum = Add(firstval, secval);
Console.WriteLine("The sum is: {0}", sum);
}
}
}
public static float Add(float num1, float num2)
{
return num1 + num2;
}
}
}
When it says
catch (FormatException)
{
Console.WriteLine("Please enter a number");
break;
}
The break; makes it so the rest of the code stops, and it displays the error. That is good, but the program also ends after that, what I want, is that the program repeats after error. Is there any way that this could happen, but it allows 1) the Console.WriteLine("Please enter a number");, 2) the program to not run the rest of the code (The part where we are asked for a second value), and 3) the program to restart for the beginning. Please let me know if that didn't make sense, as it was a hard to explain. :)
It is very simple you do not need the "break" keyword because "break" terminates the loop execution to continue execution on exception use "continue" keyword without quotes the working fiddle is here
and your code after replacing "break" with "continue" is following
using System;
namespace Calculator
{
public class Program
{
public static void Main(string[] args)
{
float input = 0;
while (input != 5)
{
Console.Clear();
Console.WriteLine("What would you like to do? Type: 1 for Addition. Write 5 to end program.");
try
{
input = float.Parse(Console.ReadLine());
}
catch (FormatException)
{
Console.WriteLine("Please enter a number");
}
//Addition
if (input == 1)
{
Console.WriteLine("Enter First Value: ");
string FirstValue = Console.ReadLine();
float firstval = 0;
try
{
firstval = float.Parse(FirstValue);
}
catch (FormatException)
{
Console.WriteLine("Please enter a number");
continue;
}
Console.WriteLine("Enter Second Value: ");
string SecondValue = Console.ReadLine();
float secval = 0;
try
{
secval = float.Parse(SecondValue);
}
catch (FormatException)
{
Console.WriteLine("Please enter a number");
continue;
}
float sum = Add(firstval, secval);
Console.WriteLine("The sum is: {0}", sum);
}
}
}
public static float Add(float num1, float num2)
{
return num1 + num2;
}
}
}

C# Play Again Number Game

I'm trying to implement the ability for the user to input Y or N to play the game again or exit, but I'm struggling to get my head round it without a massive rewrite of the code logic... I'm just getting back into C# today and am a beginner so please go easy on me :) I've already got the userContinue string ready and just want to enter a simple way of repeating the game and adding on ways of keeping score (slowly improving the game)
using System;
namespace Guess_Number_V2
{
class Program
{
static void Main(string[] args)
{
do
{
PlayGame();
Console.WriteLine("Would you play to play again? Y or N");
} while (Console.ReadLine().ToLower() == "y");
}
public static voic PlayGame()
{
Random rand = new Random();
int randNum = rand.Next(1, 11);
int incorrectGuesses = 0;
int userScore = 10;
int userGuess;
int perGuess = 1;
string userContinue;
bool correctGuess = false;
Console.WriteLine("Enter a number between 1 and 10\nScore starts at 10, one point will be deducted with each incorrect guess.");
userGuess = int.Parse(Console.ReadLine());
while (correctGuess == false)
{
if (userGuess == randNum)
{
Console.ForegroundColor = ConsoleColor.Green;
Console.WriteLine("Your guess was right, the number was {0}! Total score is {1} and you had {2} incorrect guesses.", randNum, userScore, incorrectGuesses);
correctGuess = true;
}
if (userGuess > randNum)
{
userScore -= perGuess;
incorrectGuesses++;
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine("Wrong guess again, to high!");
correctGuess = false;
}
else if (userGuess < randNum)
{
userScore -= perGuess;
incorrectGuesses++;
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine("Wrong guess again, to low!");
correctGuess = false;
}
}
}
}
}
It would help if you put your game logic in its own method. Say PlayGame(). Then you can simply write:
static void Main(string[] args)
{
do {
PlayGame();
Console.ForegroundColor = ConsoleColor.White;
Console.WriteLine("Would you play to play again? Y or N");
} while (Console.ReadLine().ToLower() == "y");
}
Also, you can simplify your logic if you make an "infinite" loop and break out of it with break; when the guess is correct.
You can read and parse the user input at the beginning of each loop.
Setting the user score the number of incorrect guesses and the red console color can be done only once also.
Tested and working code:
using System;
namespace Guess_Number_V2
{
class Program
{
static void Main(string[] args)
{
do {
PlayGame();
Console.ForegroundColor = ConsoleColor.White;
Console.WriteLine("Would you play to play again? Y or N");
} while (Console.ReadLine().ToLower() == "y");
}
private static void PlayGame()
{
Random rand = new Random();
int randNum = rand.Next(1, 11);
int incorrectGuesses = 0;
int userScore = 10;
int userGuess;
int perGuess = 1;
Console.WriteLine("Enter a number between 1 and 10\nScore starts at 10, one point will be deducted with each incorrect guess.");
while (true) {
userGuess = int.Parse(Console.ReadLine());
if (userGuess == randNum) {
Console.ForegroundColor = ConsoleColor.Green;
Console.WriteLine("Your guess was right, the number was {0}! Total score is {1} and you had {2} incorrect guesses.", randNum, userScore, incorrectGuesses);
break;
}
userScore -= perGuess;
incorrectGuesses++;
Console.ForegroundColor = ConsoleColor.Red;
if (userGuess > randNum) {
Console.WriteLine("Wrong guess again, to high!");
} else { // Must be userGuess < randNum
Console.WriteLine("Wrong guess again, to low!");
}
}
}
}
}

C# re-enter value after wrong input instead of restarting the program

so I am trying to make a multiplication table with c#, and I want that when user give a wrong input in code it should not start the program from start but just ask to re-enter that value. when I run this code and put wrong input. it will ask to display the multiplication table again. but I want that if I give wrong input at "start value" then it will only ask for re-entering the start value but not the whole input
public void Multi()
{
Console.Write("\n\n");
bool tryAgain = true;
while (tryAgain)
{
try
{
Console.Write("Display the multiplication table:\n ");
int t = Convert.ToInt16(Console.ReadLine());
Console.WriteLine("\n");
Console.WriteLine(" Start value ");
Console.WriteLine("\n");
Console.WriteLine(" End value \n");
int end = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("\n");
SwapNum(ref start, ref end);
Console.Write("\n");
Console.WriteLine("Display the table\n");
int i = start;
do
{
Console.WriteLine(t + " * " + i + " = " + t * i);
//Console.WriteLine("{0} * {1} = {2}", t, i, t*i);
i++;
} while (i <= end);
}
catch (Exception ex)
{
Console.WriteLine("Please Enter the inter number ");
}
}
}
static void SwapNum(ref int x, ref int y)
{
if (x >= y)
{
int temp = x;
x = y;
y = temp;
}
}
Change Parse into TryParse; let's extract a method for this
private static int ReadInt(string prompt) {
while (true) {
Console.WriteLine(prompt);
int result;
if (int.TryParse(Console.ReadLine(), out result))
return result;
Console.WriteLine("Sorry, it's not a correct integer value, please try again.");
}
}
...
public void Multi() {
Console.Write("Display the multiplication table:\n ");
// Now we keep asking user until the correct value entered
int t = ReadInt("Start value");
...
}

How to display highest and lowest of an array

here i ask the user for homework scores which are then averaged after discarding the smallest and largest score. i have stored the user input in an array. in my DisplayResults method im not sure how to display the lowest and highest scores that were discarded. any help is appreciated! Here is what i have so far:
class Scores
{
static void Main(string[] args)
{
double sum = 0;
double average = 0;
int arraySize;
double[] inputValues;
arraySize = HowManyScores();
inputValues = new double[arraySize];
GetScores(inputValues);
sum = CalculateSum(inputValues);
average = CaculateAverage(sum, arraySize);
DisplayResults(inputValues, average);
Console.Read();
}
public static int HowManyScores()
{
string input;
int size;
Console.WriteLine("How many homework scores would you like to enter?");
input = Console.ReadLine();
while (int.TryParse(input, out size) == false)
{
Console.WriteLine("Invalid data. Please enter a numeric value.");
input = Console.ReadLine();
}
return size;
}
public static void GetScores(double[] inputValues)
{
double scoreInput;
Console.Clear();
for (int i = 0; i < inputValues.Length; i++)
{
scoreInput = PromptForScore(i + 1);
inputValues[i] = scoreInput;
}
}
public static double PromptForScore(int j)
{
string input;
double scoreInput;
Console.WriteLine("Enter homework score #{0}:", j);
input = Console.ReadLine();
while (double.TryParse(input, out scoreInput) == false)
{
Console.WriteLine("Invalid Data. Your homework score must be a numerical value.");
input = Console.ReadLine();
}
while (scoreInput < 0)
{
Console.WriteLine("Invalid Data. Your homework score must be between 0 and 10.");
input = Console.ReadLine();
}
while (scoreInput > 10)
{
Console.WriteLine("Invalid Data. Your homework score must be between 0 and 10.");
input = Console.ReadLine();
}
return scoreInput;
}
public static double CalculateSum(double[] inputValues)
{
double sum = 0;
for (int i = 1; i < inputValues.Length - 1; i++)
{
sum += inputValues[i];
}
return sum;
}
public static double CaculateAverage(double sum, int size)
{
double average;
average = sum / ((double)size - 2);
return average;
}
public static void DisplayResults(double[] inputValues, double average)
{
Console.Clear();
Console.WriteLine("Average homework score: {0}", average);
//Console.WriteLine("Lowest score that was discarded: {0}",
//Console.WriteLine("Highest score that was discarded: {0}",
}
}
}
You basically only have to do one thing: Sorting the array after you received your input data. Then, printing the first and last value gives you the minimal and maximal score. Use
Array.Sort(intArray);
in main after calling GetScores and
Console.WriteLine("Lowest score: {0} Highest score: {1}",
inputValues[0], inputValues[inputValues.Length - 1]);
to print the results. Cheers
EDIT: The proposal by Jens from the comments using the Min/Max is probably more what you're looking for if you're not interested in complete ordering of your values.

No overload for method 'DisplayOutput' takes 0 arguments

I am trying to code a simple program to calculate netpay for employees. As far as I know my code is solid with the exception of my method call to DisplayOutput();
I understand what the error means but I do not understand how fix it to compile.
Here is my code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Project02CoddR
{
class NetPayApp
{
static void Main(string[] args)
{
Console.BackgroundColor = ConsoleColor.White;
Console.ForegroundColor = ConsoleColor.Black;
Console.Clear();
DisplayTitle();
InputData();
DisplayOutput();
TerminateProgram();
}
public static void DisplayTitle()
{
Console.WriteLine();
Console.Write("\tProject 02 - Net Pay Calculator - ");
Console.WriteLine();
DrawLine();
}
public static void InputData()
{
Console.WriteLine();
Console.Write("Please enter the number of hours worked this week: ");
int hoursWorked = Convert.ToInt32(Console.ReadLine());
Console.WriteLine();
Console.Write("Please enter your hourly rate of pay <e.g. 9.35>: ");
double payRate = Convert.ToDouble(Console.ReadLine());
Console.WriteLine();
Console.Write("Please enter your number of dependants: ");
int dependants = Convert.ToInt32(Console.ReadLine());
Console.WriteLine();
Console.Write("\n\tAre you a salesperson? <Y or N>: ");
string aValue = Console.ReadLine();
}
public static int InputSales(string aValue)
{
int sales = -1;
if (aValue == "Y" || aValue == "y" || aValue == "Yes" || aValue == "yes")
{
Console.Write("Please enter your sales amount for this period: ");
sales = Convert.ToInt32(Console.ReadLine());
}
else if (aValue == "N" || aValue == "n" || aValue == "No" || aValue == "no")
{
sales = -1;
}
return sales;
}
public static double CalculatePay(int hoursWorked, double payRate, int sales)
{
double grossPay = hoursWorked * payRate;
if (sales >= 0)
{
grossPay = grossPay +(.02*sales);
}
else if (hoursWorked > 40)
{
grossPay = grossPay + (.5*payRate) * (hoursWorked-40);
}
return grossPay;
}
public static double CalculateTax(int dependants, double grossPay)
{
int cutOff = 100 + (100 * dependants);
double taxes;
if (grossPay <= cutOff)
{
taxes = .15 * grossPay;
}
else
{
taxes = .15 * cutOff + .25*(grossPay-cutOff);
}
return taxes;
}
public static void DisplayOutput(double grossPay, double taxes)
{
double netPay = grossPay - taxes;
Console.WriteLine();
Console.WriteLine("Gross Pay: ".PadLeft(30, ' ') + grossPay);
Console.WriteLine("Taxes: ".PadLeft(30, ' ') + taxes);
Console.WriteLine("Net Pay: ".PadLeft(30, ' ') + netPay);
Console.WriteLine();
DrawLine();
}
public static void DrawLine()
{
Console.Write("______________________________________________");
}
public static void TerminateProgram()
{
Console.Write("Press any key to terminate the program...");
Console.Read();
}
}
}
DisplayOutput needs the values to display passed into it; for example:
static void Main(string[] args)
{
Console.BackgroundColor = ConsoleColor.White;
Console.ForegroundColor = ConsoleColor.Black;
Console.Clear();
DisplayTitle();
InputData();
DisplayOutput(CalculatePay(40, 50, 60), CalculateTax(4, CalculatePay(40, 50, 60)));
TerminateProgram();
}

Categories