C# list count with data validation - c#

Thanks for your feedback. I'm still getting an out of range exception. I'm debugging but can't understand why I'm getting the exception. If an int is higher than a certain other int it should work. Does it have anything to do with the length.Count?
UPDATED Code
do
{
Console.Write("Input the element that you want to exclude from the list: ");
result = int.TryParse(Console.ReadLine(), out delSelection);
tempInputDelInt = (int)(tempList[delSelection]);
tempInputDelStr = Convert.ToString(tempInputDelInt);
if (result == true && tempInputDelInt >= 0 && tempInputDelInt < tempList.Count)
{
tempList.RemoveAt(delSelection);
Console.WriteLine("\nYou've deleted the temperature " + tempInputDelStr + " from index " + delSelection);
success = false;
Console.ReadKey(true);
Console.Clear();
}
else if (result == true && tempInputDelInt >= tempList.Count || tempInputDelInt < 0)
{
Console.WriteLine("You've input a number that's outside the list. Input a digit between 0 and " + (tempList.Count - 1) + ".\n");
success = true;
Console.ReadKey(true);
}
else if (result == false)
{
Console.WriteLine("\nYou didn't input a digit, try again!\n");
success = true;
Console.ReadKey(true);
}
} while (success);
success = false;
I'm having some problems with the validation of the first else if statement. I want to catch the cases when a value outside of the array is input, but I don't manage to.
I've done a practically identical program with array.Length with success.
Is there any difference between array.List and list.Count? Is that's the problem?
Thanks in advance for your help!
do
{
Console.Write("Input the element that you want to exclude from the list: ");
result = int.TryParse(Console.ReadLine(), out delSelection);
tempInputDel = Convert.ToString(tempList[delSelection]);
if (result == true && delSelection >= 0 && delSelection < tempList.Count)
{
tempList.RemoveAt(delSelection);
Console.WriteLine("\nYou've deleted the temperature " + tempInputDel + " from index " + delSelection);
Console.ReadKey(true);
Console.Clear();
}
else if (result == true && delSelection >= tempList.Count || delSelection < 0)
{
Console.WriteLine("You've input a number that's outside the list. Input a digit between 0 and " + (tempList.Count - 1) + ".\n");
}
else if (result == false)
{
Console.WriteLine("\nYou didn't input a digit, try again!");
Console.ReadKey(true);
}
} while (result == false);

Change this
tempInputDelInt = (int)(tempList[delSelection]);
to this
tempInputDelInt = (int)delSelection;
Whatever number the user enters, you're using that as the index to determine which item to delete. So it's not a value you get from tempList.

I am assuming that your out-of-range exception happens here:
tempInputDel = Convert.ToString(tempList[delSelection]);
You cannot do this before checking, if delSelection is inside range of tempList. Move it inside first if block.
General advice:
You can use a debugger to go from statement to statement step-by-step to find the exact source code position where (e.g.) an exception is thrown.

Related

How do you properly use a Console.Readline() in a loop with string integer? [duplicate]

This question already has answers here:
How to replace multiple if statements i to more compact code/class in C#?
(5 answers)
Closed last year.
I'm baby-new to c# and building a project on mental health with multiple objects - starting with loops. Is there more tactful way to approach this code?
I ran basic code input via following:
Console.WriteLine("How are you feeling (1-bad to 5 great)?");
var userInput = Console.ReadLine();
Console.WriteLine(" Mood: " + userInput);
if (! Int32.TryParse(userInput, out x))
{
Console.WriteLine("Invalid data input");
}
else if (x == 1)
{
Console.WriteLine(" very low.");
}
else if (x == 2)
{
Console.WriteLine(" low.");
}
else if (x == 3)
{
Console.WriteLine(" average.");
}
else if (x == 4)
{
Console.WriteLine(" good.");
}
else if (x == 5)
{
Console.WriteLine(" very good.");
}
try this, it is more compact code
var invalidData = false;
var x = 0;
var moods = new string[] { " very low.", " low.", " average.", " good.", " very good." };
do
{
Console.WriteLine("How are you feeling(1 - bad to 5 great)?");
var userInput = Console.ReadLine();
Console.WriteLine(" Mood: " + userInput);
if (!Int32.TryParse(userInput, out x) || x < 1 || x > 5)
{
Console.WriteLine("Invalid data input");
invalidData = true;
}
else invalidData = false;
}
while (invalidData);
Console.WriteLine(moods[x-1]);

C# Go to beginning of loop (continue or break?)

This program randomly creates a number between 1 and 50 that the user needs to guess. I want to restart the while loop when the user's guess is incorrect. I have tried using break and continue to do this, but either I am doing it wrong or it is not the best solution. Also, when the user input is incorrect they are asked if they want to guess again. I also tried exiting that loop with break or continue with similar results. Any suggestions?
Console.WriteLine("I am thinking of a whole number between 1 and 50. Enter your guess.");
string userGuess;
Random rnd = new Random();
int compNum = rnd.Next(1, 50);
int guessToInt;
int numOfTries = 0;
string cont;
bool correct = false;
//TODO Delete this line when finished
Console.WriteLine($"Answer " + compNum);
//Trying to get new user input if guess is wrong
while (correct == false)
{
//correct = false;
numOfTries++;
userGuess = Console.ReadLine();
guessToInt = Int32.Parse(userGuess);
if (guessToInt == compNum)
{
numOfTries++;
correct = true;
Console.WriteLine($"Your guess is correct! The number was " + compNum + ". Congratulations. It only took you " + numOfTries + " guess(es).");
}
else if (guessToInt < 1 || guessToInt > 50)
{
Console.WriteLine("Incorrect input. Enter a whole number between 1 and 50. Try again.");
//numOfTries++;
correct = false;
continue;
}
else if (guessToInt != compNum)
{
//How do I get new user input?
Console.WriteLine("Your guess is incorrect. Would you like to try again? Y or N?");
//numOfTries++;
correct = false;
cont = Console.ReadLine();
if (cont == "Y")
{
continue;
}
else Console.WriteLine("Bye."); Environment.Exit(0);
}
}
Few problems:
You don't have to set the boolean to false each time. It is already set to false at start
else Console.WriteLine("Bye."); Environment.Exit(0);
Since you didn't add curly brackets (which I strongly advise you to never do),
Only the first command will operate under the statement.
The "Environment.Exit" will always occur.
For the rest, I added the fixes to your code.
Console.WriteLine("I am thinking of a whole number between 1 and 50. Enter your guess.");
string userGuess;
Random rnd = new Random();
int compNum = rnd.Next(1, 50);
int guessToInt;
int numOfTries = 0;
string cont;
bool correct = false;
//TODO Delete this line when finished
Console.WriteLine($"Answer " + compNum);
//Trying to get new user input if guess is wrong
while (correct == false)
{
//correct = false;
numOfTries++;
userGuess = Console.ReadLine();
guessToInt = Int32.Parse(userGuess);
if (guessToInt == compNum)
{
numOfTries++;
correct = true;
Console.WriteLine($"Your guess is correct! The number was " + compNum + ". Congratulations. It only took you " + numOfTries + " guess(es).");
}
else if (guessToInt < 1 || guessToInt > 50)
{
Console.WriteLine("Incorrect input. Enter a whole number between 1 and 50. Try again.");
//numOfTries++;
//**correct = false; --> No need, correct was already false
//**continue; --> No need, will continue anyway
}
else if (guessToInt != compNum)
{
//How do I get new user input?
Console.WriteLine("Your guess is incorrect. Would you like to try again? Y or N?");
cont = Console.ReadLine();
//numOfTries++;
//**correct = false; --> No need, correct was already false
//** if (cont == "Y") --> No need, will continue anyway
//** {
//** continue;
//** }
// else Console.WriteLine("Bye."); Environment.Exit(0); -->
//** "else" without brackets will
if (cont != "Y")
{
break;
}
Console.WriteLine("Enter your next guess:");
}
}
NOTE: I haven't touched the "numOfTries" feature since not mentioned in the question

Positive Or Negative - If Statements

Alright so in the book im reading its telling me to write a program that asks the user for two multiplication numbers and then it will print out whether the result should be positive or negative.
The rule is that i cannot take two numbers and multiply them, and then check if the result is greater than or less than zero. Instead if the two numbers have the same sign (both positive or both negative) the result is positive. If they have different signs, the result is negative.
I did it like this ( also i added int anresult = first * second; <- do i need that?) because if i remove it it still works, but the book wants it in multiplication. so im not sure if that piece of code is doing anything at all
Console.WriteLine("Enter First Nuumber: ");
string firstAsString = Console.ReadLine();
int first = Convert.ToInt32(firstAsString);
Console.WriteLine("Enter Second Nuumber: ");
string secondAsString = Console.ReadLine();
int second = Convert.ToInt32(secondAsString);
int anresult = first * second;
if (first >= 0 && second > 0 || first < 0 && second < 0)
Console.WriteLine("Your number will be Positive");
else
Console.WriteLine("Your number will be negative");
Console.ReadLine();
But the book did it like this
Console.WriteLine("Enter First Nuumber: ");
string firstAsString = Console.ReadLine();
int first = Convert.ToInt32(firstAsString);
Console.WriteLine("Enter Second Nuumber: ");
string secondAsString = Console.ReadLine();
int second = Convert.ToInt32(secondAsString);
bool firsNumberPositive;
bool secondNumberPositive;
if (first > 0) {
firsNumberPositive = true;
}
else
{
firsNumberPositive = false;
}
if (second > 0)
{
secondNumberPositive = true;
}
else
{
secondNumberPositive = false;
}
if (firsNumberPositive && secondNumberPositive || !firsNumberPositive && !secondNumberPositive)
Console.WriteLine("Answer Is Positive");
else
if (!firsNumberPositive && secondNumberPositive || firsNumberPositive && !secondNumberPositive)
Console.WriteLine("Answer Is Negative");
Console.ReadLine();
isnt my way the same as the books way? because the book shows
if (first > 0) {
firsNumberPositive = true;
}
which is using the numbers just like i am to display positive and negative
heres mine, same thing?..
if (first >= 0 && second > 0 || first < 0 && second < 0)
Console.WriteLine("Your number will be Positive");
else
Console.WriteLine("Your number will be negative");
The solution presented in the book doesn't consider the condition where the input is 0, so it will behave differently than the code you wrote.
Your solution does not output the same result as the one in the book. Just try it with both first and second 0. Your code will say the result is negative while the book's solution will say it is positive.
In my opinion, 0 is neither a positive nor negative number and should be treated separately. So here's my solution:
if (first == 0 || second == 0) {
Console.WriteLine("The result is 0");
} else if ((first > 0) != (second > 0)) { // here, it might look a little weird but I'm just checking whether the signs are the same.
Console.WriteLine("The result is negative");
} else {
Console.WriteLine("The result is positive");
}

C# Validate input as double

I would like to validate my input as bigger than or equal to 0 and as double. This is what i have so far:
string aBalBeginS;
double abalbeginVal;
Console.Write("Account Balance at the beginning: $");
aBalBeginS = Console.ReadLine();
abalbeginVal = double.Parse(aBalBeginS);
if (aBalBeginS == "" || abalbeginVal <= 0)
{
Console.WriteLine("Invalid data entered - no value redorded");
aBalBeginS = null;
}
How do i add to check if input is a number. I tried double.TryParse, but without luck.
You are on the right track with double.TryParse()
double abalbeginVal;
bool parsed = double.TryParse(aBalBeginS, out abalbeginVal);
if (parsed && abalbeginVal >=0.0)
{
// We're good
}
else
{
// Did not pass check
}
Found the solution:
Console.Write("Account Balance at the beginning: $");
aBalBeginC = Console.ReadLine();
//abalbeginVal = double.Parse(aBalBeginC);
if (double.TryParse(aBalBeginC, out abalbeginVal) == false || aBalBeginC == "" || abalbeginVal <= 0)
{
Console.WriteLine("Invalid data entered - no value redorded");
aBalBeginC = null;
}
Thx.

How could I convert this goto into a do while loop?

class Program
{
static void Main(string[] args)
{
string choice = string.Empty;
do
{
start:
int output = 0;
int number = 0;
Console.WriteLine("Please input a number for it to be counted!");
bool conversion = int.TryParse(Console.ReadLine(), out output);
if (number < 1000)
{
switch (conversion)
{
case true:
while (number <= output)
{
Console.Write(number + " ");
number += 2;
}
break;
case false:
Console.WriteLine("ERROR: INVALID INPUT!");
goto start;
}
}
else
{
Console.WriteLine("APPLICATION ERROR: NUMBER MUST BE BELOW OR AT 1000 TO PREVENT OVERFLOW!");
return;
}
do // Here is the beginning of the do code
{
Console.WriteLine("\n Do you want to continue - Yes or No");
choice = Console.ReadLine();
if (choice.ToUpper() != "YES" && choice.ToUpper() != "NO")
{
Console.WriteLine("ERROR INVALID INPUT: Only input Yes or No!");
}
} while (choice.ToUpper() != "YES" && choice.ToUpper() != "NO");
} while (choice.ToUpper() == "YES");
}
}
I'm using several do while loops in this statement however I'm trumped on how I would put in a loop "ERROR INVALID INPUT:" result when a user puts in anything other than the limits of the assigned integers (i.e. putting decimals or fractions) or if they put a string. I simply used goto because I'm having trouble finding out where to put the do while loop statement. If someone could simply show me how I might replace that one goto with a do while loop then I would be very greatful. (Note if you show me ways I could optimize my code better since I'm still new I probably won't understand it but your welcome to give it your best shot!)
Short answer:
The keyword continue means to go back to the beginning of the loop. Note that this will recheck the loop condition and break if it is false. Also, most people find do-while loops less readable (and they are really rarely necessary), so try using while loops instead.
There is also the keyword break which will simply exit the loop. (not just for switch-case!)
A more readable version would look something like this:
string userAnswer = "yes";
// while is usually more readable than do-while
while (userAnswer == "yes")
{
Console.WriteLine("Please input a number for it to be counted!");
int number;
// Ask for new input until the user inputs a valid number
while (!int.TryParse(Console.ReadLine(), out number))
{
Console.WriteLine("Invalid number, try again");
}
if (number < 1000)
{
// Print from 0 to number, jumping in 2's
for (int i = 0; i <= number; i += 2)
Console.WriteLine(i + " ");
}
else
{
Console.WriteLine("APPLICATION ERROR: NUMBER MUST BE BELOW OR AT 1000 TO PREVENT OVERFLOW!");
continue; // Jump back to the start of this loop
}
Console.WriteLine("Continue? (Yes / No)");
userAnswer = Console.ReadLine().ToLower();
// Ask for new input until the user inputs "Yes" or "No"
while (userAnswer != "yes" && userAnswer != "no")
{
Console.WriteLine("Invalid input. Continue? (Yes / No)");
userAnswer = Console.ReadLine().ToLower();
}
}
Hey I'll post some code that may help and offer some advice. Basically declare a bool named 'loopCompleted' which will continue the do while loop until you set it to true. The downside is that it will not instantly exit the loop like return/goto/etc but this is not a problem in most cases.
You may want to use if/else instead of switch(conversion), its sort of interesting to see it done that way but its a bit over the top :)
If Int.TryParse() doesnt already return false for fractional values (e.g. [15.08] returns [true] with [15] ). Then you can store Console.ReadLine() before using TryParse, then use stringName.Contains() to check for the '.' Basically, if the conversion succeeds you also check if it contained the decimal point.
Another way to check is to do float.TryParse() then check if it is a fractional value.
bool fraction = false;
if( number % 1.0f > 0)
fraction == true;
% is called modulus, it returns the remainder of A / B
If a number has a remainder when divided by 1 it must be a fractional value.
//start:
bool loopCompleted = false;
do
{
int output = 0;
int number = 0;
Console.WriteLine("Please input a number for it to be counted!");
bool conversion = int.TryParse(Console.ReadLine(), out output);
if (conversion && number < 1000)
{
while (number <= output)
{
Console.Write(number + " ");
number += 2;
}
loopCompleted = true;
}
else
{
if(conversion == false)
{
Console.WriteLine("ERROR: INVALID INPUT!");
}
else
{
Console.WriteLine("APPLICATION ERROR: NUMBER MUST BE BELOW OR AT 1000 TO PREVENT OVERFLOW!");
}
}
} while(!loopCompleted)

Categories