I have two modules, with an if statement.
Here are the two code snippets.
int sum;
int input;
singleDigit(ref firstRandom, ref secondRandom);
Console.Write("{0} + {1} = : ", firstRandom, secondRandom);
input = Convert.ToInt16(Console.ReadLine());
sum = firstRandom + secondRandom;
if (firstRandom + secondRandom == sum)
{
checkanswergradeoneaddition();
}
else
{
checkanswergradeoneadditionFalse();
}`
Here is the module the latter is referring too. Please bear in mind, I have only been in my programming course since September 2nd.
static void checkanswergradeoneadditionFalse()
{
Random rnd = new Random();
int responseTwo = rnd.Next(0, 3);
switch (responseTwo)
{
case 1:
Console.WriteLine("Incorrect, mush!");
break;
case 2:
Console.WriteLine("Wrong again, Einstein");
break;
default:
Console.WriteLine("Default");
break;
}
}
It's not working as intended.
look at this:
sum = firstRandom + secondRandom;
if (firstRandom + secondRandom == sum)
{
checkanswergradeoneaddition();
}
It makes no sense. if sum is assigned A+B then A+B will always == sum. The "else" will never run.
maybe it's supposed to be
if(input==sum)
I think I get what you're trying to say. Your firs if statement will always be true, because it does not compare any of the users input.
int sum;
int input;
singleDigit(ref firstRandom, ref secondRandom);
Console.Write("{0} + {1} = : ", firstRandom, secondRandom);
input = Convert.ToInt16(Console.ReadLine());
sum = firstRandom + secondRandom;
if (firstRandom + secondRandom == sum)
{
checkanswergradeoneaddition();
}
else
{
checkanswergradeoneadditionFalse();
}`
Try changing it to:
int sum;
int input;
singleDigit(ref firstRandom, ref secondRandom);
Console.Write("{0} + {1} = : ", firstRandom, secondRandom);
input = Convert.ToInt16(Console.ReadLine());
sum = firstRandom + secondRandom;
// Changed the first 'if' statement to compare the users input with the sum.
if (input == sum)
{
checkanswergradeoneaddition();
}
else
{
checkanswergradeoneadditionFalse();
}`
Take note of the comment above the first if statement.
Related
How can I make a program in C# that gets 3 digits from the user and outputs the smallest one? It's gonna be as a Console App.
I tried this and gave me an error (I may be stupid):
if (a<b<c)
{
min=a;
Console.WriteLine("Min: " + min);
I don't now what else should I do, I'm new to C#.
There's nothing wrong with being new, and you aren't stupid just because you aren't sure how something works.
Think of it like this:
We need to have a variable to hold this minimum value:
int min;
First, you need to compare two values to get the smallest between them:
if (a < b)
min = a;
else
min = b;
Now that you have the minimum between those two, compare that value to your third input:
if (c < min)
min = c;
If c is less than the current min value, you adjust to c, otherwise you already had your minimum value in the first comparison.
Here is a full example for you to play with as well:
int a = 4;
int b = 2;
int c = 1;
int min;
if (a < b)
min = a;
else
min = b;
if (c < min)
min = c;
Console.WriteLine("Lowest value is {0}", min);
Try this.
if (a < b && a < c)
{
Console.WriteLine("Min: " + a);
}
else if (b < c)
{
Console.WriteLine("Min: " + b);
}
else
{
Console.WriteLine("Min: " + c);
}
Here's a solution that should work:
int a, b, c, min;
Console.WriteLine("Please enter three digits:");
a = int.Parse(Console.ReadLine());
b = int.Parse(Console.ReadLine());
c = int.Parse(Console.ReadLine());
min = Math.Min(Math.Min(a, b), c);
Console.WriteLine("Min: " + min);
Just run this code and write if you want me to explain smth. It will be nice if you mark this answer as correct if that's helped you
#region Begin Message
string s = "\"s\"";
Console.WriteLine(#$"Here is example of the code.
Please contact me if you did not understand smth.
You should write as many numbers as u wanna, the program returns numbers in ascending order.
Write {s} to stop
");
#endregion
#region Main Part
List<float> numbers = new List<float>();
while (true)
{
Console.WriteLine($"{numbers.Count + 1} number: ");
string input = Console.ReadLine();
if (input.ToLower().Contains("s"))
{
Console.WriteLine(SortNumbers(numbers) ?? "There are no numbers created");
break;
}
else
{
try
{
float number = float.Parse(input);
numbers.Add(number);
}
catch (Exception ex) { Console.WriteLine("You should write a number \n"); }
}
}
#endregion
string? SortNumbers(List<float> numbers)
{
numbers.Sort();
string? returnedNumbers = null;
if (numbers.Count != 0)
{
returnedNumbers += "\nNumbers: ";
for (int i = 0; i < numbers.Count; i++)
{
returnedNumbers += $"{numbers[i]}, ";
}
}
return returnedNumbers;
}
So I have this code where you enter your "area code" and then you enter how long you would like the call to be. This is basically a simple calculator that would find the cost of how much a call would be depending on your area code. I am having trouble trying to figure out how to keep the loop running if I enter in an invalid area code. As of now if I enter in an invalid area code the entire program will just end in the command prompt. Heres the code:
using System;
using static System.Console;
namespace Chapter6._1
{
class Program
{
static void Main()
{
// array info //
int[] phoneAreacode = { 608, 414, 262, 815, 715, 920 };
double[] phoneCost = { .05, .10, .07, .24, .16, .14 };
// declaring variables //
int x;
int areaCode;
double cost = 0;
int callLength;
bool validAreacode = false;
// start of actual code //
Write("Enter in the area code you want to call: ");
areaCode = Convert.ToInt32(ReadLine());
x = 0;
while (x < phoneAreacode.Length && areaCode != phoneAreacode[x])
++x;
if(x != phoneAreacode.Length)
{
validAreacode = true;
cost = phoneCost[x];
}
if (validAreacode)
{
Write("Enter in the length of your call: ");
callLength = Convert.ToInt32(ReadLine());
double finalCost = callLength * cost;
WriteLine("Your call to area code " + areaCode + " for " + callLength + " minutes will cost " + finalCost.ToString("C"));
}
else
{
WriteLine("YOU MUST ENTER A VALID AREA CODE!");
}
}
}
}
You might wrap your Read and Check routine into another while-loop:
bool validAreacode = false;
while(!validAreacode)
{
// start of actual code //
Write("Enter in the area code you want to call: ");
areaCode = Convert.ToInt32(ReadLine());
x = 0;
while (x < phoneAreacode.Length && areaCode != phoneAreacode[x])
++x;
if(x != phoneAreacode.Length)
{
validAreacode = true;
cost = phoneCost[x];
}
else
{
WriteLine("YOU MUST ENTER A VALID AREA CODE!");
}
}
This is the simplest solution for you (not so much changes in your code required). But your code still has the problems. Your program will be crashed if user tries to print any not digit character instead of area code.
You can do a do-While here:
Basically when you do do-while you force the code on the do to be done until the condition in the while is completed. in your case, you need to add the checking of the pohne number inside the do statement, and to know if the person selected a correct value, you can do Array.FindIndex():
this will be your do-while loop, also i chaned your x for index try to use names for the variables that have some meaning. (index is not perfect anyway)
do
{
Write("Enter in the area code you want to call: ");
areaCode = Convert.ToInt32(ReadLine());
index = Array.FindIndex(phoneAreacode, w => w == areaCode);
if (index >= 0)
{
validAreacode = true;
}
else
{
WriteLine("YOU MUST ENTER A VALID AREA CODE!");
}
} while (!validAreacode);
and this will be your entire main method:
int[] phoneAreacode = { 608, 414, 262, 815, 715, 920 };
double[] phoneCost = { .05, .10, .07, .24, .16, .14 };
// declaring variables //
int index;
int areaCode;
int callLength;
bool validAreacode = false;
// start of actual code //
do
{
Write("Enter in the area code you want to call: ");
areaCode = Convert.ToInt32(ReadLine());
index = Array.FindIndex(phoneAreacode, w => w == areaCode);
if (index >= 0)
{
validAreacode = true;
}
else
{
WriteLine("YOU MUST ENTER A VALID AREA CODE!");
}
} while (!validAreacode);
Write("Enter in the length of your call: ");
callLength = Convert.ToInt32(ReadLine());
double finalCost = callLength * phoneCost[index];
WriteLine("Your call to area code " + areaCode + " for " + callLength + " minutes will cost " + finalCost.ToString("C"));
As you can see you can also remove the while you have to loop the array and the if-else for the valid codes. assuming that when the code reach that point, the area is correct.
It's a good practice to try to remove the number of if-else.
You probably need to loop the entire code section, something like this
while (true)
{
Write("Enter in the area code you want to call: ");
var input = ReadLine();
if (input == "Exit")
break;
areaCode = Convert.ToInt32(input);
x = 0;
while (x < phoneAreacode.Length && areaCode != phoneAreacode[x])
++x;
if(x != phoneAreacode.Length)
{
validAreacode = true;
cost = phoneCost[x];
}
else if (validAreacode)
{
Write("Enter in the length of your call: ");
callLength = Convert.ToInt32(ReadLine());
double finalCost = callLength * cost;
WriteLine("Your call to area code " + areaCode + " for " + callLength + " minutes will cost " + finalCost.ToString("C"));
}
else
{
WriteLine("YOU MUST ENTER A VALID AREA CODE!");
}
}
Don't forget to add a check for when user types something that's not a digit
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");
...
}
I'm creating a program for a college assignment and the task is to create a program that basically creates random times table questions. I have done that, but need to error check the input to only accept integer inputs between 1-100. I can not find anything online only for like java or for text box using OOP.
Here is my code:
static void help()
{
Console.WriteLine("This program is to help children learn how to multiply");
Console.WriteLine("The program will create times table questions from 1-10");
Console.WriteLine("The user will be given 10 random questions to complete");
Console.WriteLine("The user will get a score out of 10 at the end");
Console.WriteLine("If the user gets the answer wrong, the correct answer will be displayed");
Console.WriteLine("");
Console.ReadLine();
Console.Clear();
}
static void Main(string[] args)
{
int Random1 = 0;
int Random2 = 0;
int Answer;
int Count = 0;
int Score = 0;
int input = 0;
String choice;
Console.WriteLine("To begin the Maths test please hit any key");
Console.WriteLine("If you need any help, just, type help");
choice = Console.ReadLine();
if (choice == "help")
{
help();
}
while (Count != 10)
{
Random numbers = new Random();
Random1 = numbers.Next(0, 11);
Count = Count + 1;
Random numbers2 = new Random();
Random2 = numbers.Next(0, 11);
Console.WriteLine(Random1 + "x" + Random2 + "=");
input = int.Parse(Console.ReadLine());
Answer = Random1 * Random2;
if (Answer == input)
{
Console.ForegroundColor = ConsoleColor.Green;
Console.WriteLine("Correct");
Score = Score + 1;
Console.ResetColor();
}
else
{
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine("Thats the wrong answer, the correct is " + Answer);
Console.ResetColor();
}
}
if (Score > 5)
{
Console.ForegroundColor = ConsoleColor.Green;
Console.WriteLine("Good job you got more than 5 answers correct! With a score of " + Score + " out of 10");
Console.ResetColor();
Console.ReadLine();
}
else if (Score < 5)
{
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine("");
Console.WriteLine("Try again you got less than 5 correct! With a score of " + Score + " out of 10");
Console.ResetColor();
Console.ReadLine();
}
}
}
}
Firstly, I suggest you to use TryParse instead of Parse to prevent unexpected errors because of invalid inputs. So, try something like that;
Random numbers = new Random();
Random1 = numbers.Next(0, 11);
Count = Count + 1;
Random numbers2 = new Random();
Random2 = numbers.Next(0, 11);
Console.WriteLine(Random1 + "x" + Random2 + "=");
//Modified
int input = 0;
while (true)
{
if (!int.TryParse(Console.ReadLine(), out input))
{
Console.WriteLine("Invalid Input. Please enter a valid integer.");
}
else
{
if (input >= 1 && input <= 100)
{
break;
}
Console.WriteLine("Invalid Input. Please enter a integer between 1-100.");
}
}
//Modified
I'd simply use a loop that will keep asking for input until it
matches your requirement:
int MinVal = 1; // No magic numbers! You may consider placing them in a config
int MaxVal = 100; // or as static readonly class members (a bit like "const").
int input = -1;
for(;;) // "empty" for-loop = infinite loop. No problem, we break on condition inside.
{
// attempt getting input from user
bool parseOK = int.TryParse(Console.ReadLine(), out input);
// Exit loop if input is valid.
if( parseOK && input >= MinVal && input <= MaxVal ) break;
Console.WriteLine( "Errormessage telling user what you expect" );
}
You may also consider granting only N trys to get the input right.
A few hints:
do not use "magic numbers". Define constants or put numbers into Properties/Settings. Name them self-explanatory and document why you chose the value they happen to have.
The errormessage should tell the user what an expected valid input is (as opposed to what they typed in) not just that their input was invalid.
Whats about this?
input = int.Parse(Console.ReadLine());
if(input > 1 && input < 100){
// valid
}else{
// invalid
}
I am new to C# and trying to create a GPA calculator using a sentinel controlled loop. To end the loop, I want the user to enter an 'x', but it is throwing an exception. I'm pretty sure it is because 'x' is not a double type, but I am not sure how I can make it work. I was using a number to exit before but it kept being added to the gradeTotal. Any suggestions would be great! Thanks!
Code:
class Program
{
static void Main(string[] args)
{
double gradeTotal = 0;
int[] score = new int[100];
string inValue;
int scoreCnt = 0;
Console.WriteLine("When entering grades, use a 0-4 scale. Remember;
A = 4, B = 3, C = 2, D = 1, F = 0");
Console.WriteLine("Enter grade {0}: ((X to exit)) ", scoreCnt + 1);
inValue = Console.ReadLine();
gradeTotal += double.Parse(inValue);//This may be a problem area
while (inValue != "x")
{
if (int.TryParse(inValue, out score[scoreCnt]) == false)
Console.WriteLine("Invalid data -" + "0 stored in array");
++scoreCnt;
Console.WriteLine("Enter Score{0}: ((X to exit)) ", scoreCnt +
1);
inValue = Console.ReadLine();
gradeTotal += double.Parse(inValue);//This is a problem area
}
Console.WriteLine("The number of scores: " + scoreCnt);
Console.WriteLine("Your GPA is: " + gradeTotal);//Obviously not the
//right calculation, just trying to figure it out
Console.ReadLine();
}
}
Least effort
Instead of
gradeTotal += double.Parse(inValue);//This is a problem area
Try
if (inValue == "X") break;
gradeTotal += double.Parse(inValue);
More robust
double d;
var ok = double.TryParse(inValue, out d);
if (!ok) break;
gradeTotal += d;
You have zero validation on the inValue before trying to parse it. That's the problem. How you resolve this is up to you. Here's a couple suggestions:
wrap the code in a try...catch...
try {
grandTotal += double.Parse(inValue);
} catch (Exception e) {
Console.WriteLine("Invalid input!");
}
Use Regular Expressions to validate user input and return error if not a number
(System.Text.RegularExpressions.Regex)