How to count users answers in Console - c#

First days with C# and already stuck. My question is how to count all the answers that a user gave trying to find out what the random number is? And then put-it in the las sentence withe the right answer. That's how the "quiz" looks like:
public static void Main(string[] args)
{
Console.WriteLine("The secret number\n");
Random randomerare = new Random();
int slump_tal = randomerare.Next(1, 101);
Console.WriteLine("Write your number and we'll see where it lands:\n");
string user_nr = Console.ReadLine();
int tal = Convert.ToInt32(user_nr);
Console.WriteLine();
while (tal > slump_tal)
{
Console.WriteLine("Wrong! Your number is too big!\n");
user_nr = Console.ReadLine();
tal = Convert.ToInt32(user_nr);
}
while (tal < slump_tal)
{
Console.WriteLine("Wrong Your number is too low!\n");
user_nr = Console.ReadLine();
tal = Convert.ToInt32(user_nr);
}
while (tal == slump_tal)
{
Console.WriteLine("Bravo! That's the correct number\n");
break;
}
Console.WriteLine("The secret number was: {0}\n\nPush the button to finish", slump_tal);
Console.ReadKey(true);
}

There are 2 steps in your code. And you mixed them up.
Step 1: do a while loop to keep getting input from user.
Step 2: inside each loop, you need to validate the input against the number.
It should be 1 big while() loop with 3 if (). Let me know if you need example code.

I would do it like this:
1. Get a number
2. While the user is not hitting the right number:
2.1 let the user know if the number was too big or too small
2.2 ask for another number
2.3 count number-of-attems + 1
3. If the user arrived here, it means it has the number right, print number-of-attems
In code, this could look like this:
public static void Main(string[] args)
{
Console.WriteLine("The secret number\n");
Random randomerare = new Random();
int slump_tal = randomerare.Next(1, 101);
Console.WriteLine("Write your number and we'll see where it lands:\n");
Console.WriteLine();
int user_nr = Convert.ToInt32(Console.ReadLine());
// Here you can store the attempts
int attempts = 1;
// While the user provides the wrong answer, we iterate
while(slump_tal != user_nr)
{
// We add 1 to the counter
attempts++;
if (slump_tal > slump_tal)
{
Console.WriteLine("Wrong Your number is too low!\n");
}
else
{
Console.WriteLine("Wrong! Your number is too big!\n");
}
user_nr = Convert.ToInt32(Console.ReadLine());
}
Console.WriteLine($"Bravo! That's the correct number. you did it in {attempts} attemps");
Console.WriteLine("The secret number was: {0}\n\nPush the button to finish", slump_tal);
Console.ReadKey(true);
}

Related

How to count digits of number without loop?

I am trying to make an app where you can add phone numbers and other stuff and I want to check if the number is in correct format so i have been using this loop to check this
int numer = int.Parse(Console.ReadLine());
int count = 0;
int number = numer;
while (number > 0)
{
number /= 10;
count++;
if (number)
{
Console.WriteLine(count);
stringList.Add(nazwa);
intList.Add(numer);
//Console.Clear();
Console.WriteLine($"You added new contact {nazwa} which number is {numer} ");
Console.WriteLine();
}
else
{
Console.WriteLine(count);
//Console.Clear();
Console.WriteLine("This number is in a wrong format!");
Console.WriteLine();
}
}
The problem is when i will type number that has 10 digits program will add this number to the database and after that is going to send error to the user.
To validate it you just need:
string input = Console.ReadLine();
bool valid = input.Length == 10 && input.All(char.IsDigit);
I just saw that you want to validate phone-numbers. Well, then this is not sufficient. But if a phone number is valid depends on the country/region. Search for phone number regex(for example in US).

How can I display a list of numbers that start with a user input in C# and the .NET Framework?

namespace A3PFJBJLP1
{
class Program
{
static void Main(string[] args)
{
// option 1 by parker farewell
Console.WriteLine("~ option 1 ~");
Console.WriteLine("please input a number: ");
for (int StartingNum = Convert.ToInt32(Console.ReadLine()); StartingNum < 20; StartingNum++)
{
Console.WriteLine(StartingNum);
}
Console.ReadLine();
}
}
}
So far this is the code I've tried and I can display the numbers in a list, but only if the number is 20 or less when I need to make a list that displays 20 whole numbers that come after the number inputted by the user
You were close. If you start at a number userInput, you want to display 20 numbers after it you could update the loop as follows.
int userInput = Convert.ToInt32(Console.ReadLine()); // get and store user input
for (int startingNum = userInput; startingNum < userInput + 20; startingNum++)
{
Console.WriteLine(startingNum + 1); // display number after startingNum
}

how do I write in the same line that the user wrote?

The user enters a numbers and the program should make a sideways graph by writing "-" * the amount of digits in the number, but it writes the "-" a line under the user input
Current output:
Expected output:
static void Main(string[] args)
{
int num1, num2;
Console.WriteLine("how many numbers will you want to enter?");
num1 = int.Parse(Console.ReadLine());
Console.WriteLine("Enter " + num1 + " numbers");
for(; num1 > 0; num1--)
{
num2 = int.Parse(Console.ReadLine());
Hi(num2);
}
}
static void Hi(int num)
{
while(num != 0)
{
num /= 10;
Console.Write("-");
}
Console.WriteLine()
}
You can get and set the cursor position in the console, so if you remember which line it is on before the user presses enter for the number entry, you can put the cursor back on that line.
Also, to print a number of dashes of the length of the input, it is not necessary for the input to be digits (or you would have checked for that).
Something like this should be suitable:
static void Main(string[] args)
{
Console.Write("How many numbers will you want to enter? ");
int num1 = int.Parse(Console.ReadLine());
Console.WriteLine("Enter " + num1 + " numbers");
for (; num1 > 0; num1--)
{
int currentLine = Console.CursorTop;
string num2 = Console.ReadLine();
Console.SetCursorPosition(20, currentLine);
Console.WriteLine(new string('-', num2.Length));
}
Console.WriteLine("\r\n(Press enter to leave program.)");
Console.ReadLine();
}
Sample output:
How many numbers will you want to enter? 4
Enter 4 numbers
1 -
435 ---
What happens long wi-----------------------
(Press enter to leave program.)
Use a method like the following:
public string getKeyBuffer()
{
string buffer = "";
do
{
var charIn = Console.ReadKey(true);
if (charIn.Key == ConsoleKey.Enter) break;
buffer += charIn.KeyChar;
Console.Write(charIn.KeyChar);
} while (true);
return buffer;
}
This will echo each key pressed and then return all the keys pressed once the user presses the enter key without echoing the enter key.
The best solution would be to write to something other than the console, where you would have absolute control over what is displayed and where.
Another solution would be to format a string in your code, then clear the console and write the entire thing each time.
Another solution would be to keep track of where you are and move the console cursor using Console.SetCursorPosition. However, this is rarely a satisfying solution given the existence of nicer output alternatives.
You can move the cursor up one line with Console.CursorTop--;, avoiding the necessity of keeping track of which line you are on.

C# How do I error check the input ensuring only integers between 1-100 are accepted

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
}

How to add a function that finds largest and smallest values and displays them

I made a program that asks you to enter a few numbers less than 100, and then takes the numbers you entered and tells you which ones were valid entries. What I want to add is a feature that takes those valid entries and finds the smallest and largest numbers. After it finds the smallest and largest values I want them to be displayed under where it says "Invalid entries:." Can anyone help me with adding this?
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Programming_Exercise_2_Chapter_6
{
class Program
{
static void Main(string[] args)
{
string answer;
do
{
Console.Clear();
Header();
int number;
string indata;
List<int> validEntries = new List<int>();
List<string> invalidEntries = new List<string>();
while (true)
{
Console.WriteLine("Insert numbers less than 100: ");
indata = Console.ReadLine();
if (Int32.TryParse(indata, out number))
{
if (number <= 100 && number > 0)
validEntries.Add(number);
else
invalidEntries.Add(number.ToString());
}
else
invalidEntries.Add(indata);
Console.WriteLine("Press N to stop. Press enter to continue.");
indata = Console.ReadLine();
Console.Clear();
if (indata == "n"|| indata == "N")
break;
}
DisplayEntries(validEntries, invalidEntries);
Console.ReadLine();
Console.WriteLine("Do you want to try again?(Enter Y for Yes, or N for No)");
answer = Console.ReadLine();
}
while (answer == "Y" || answer == "y");
}
static void DisplayEntries(List<int> validEntries, List<string> invalidEntries)
{
Console.WriteLine("Your valid entries were: ");
foreach (int i in validEntries)
Console.WriteLine(i);
Console.WriteLine();
Console.WriteLine("Your invalid entries were: ");
foreach (string s in invalidEntries)
Console.WriteLine(s);
}
static void Header()
{
Console.WriteLine("\tNumber Validation App");
Console.WriteLine("Please enter a few numbers less than 100.\nValid entries will be displayed.");
Console.WriteLine("");
}
}
}
If I understood your question, you want to have the smallest and largest entry from your integer list?
In that case you can simply sort the list and retrieve the first / last entry of the sorted list:
validEntries.Sort();
var smallest = validEntries.First();
var highest = validEntries.Last();
Is that what you were looking for?
So you have a list of integers(numbers). ranging between 1 and 100. all of the stored in validEntries.
So you have to go through all numbers in the list, when you find a high one you store it and compare it to the next number in the list.
int highest_nr = 0;
int lowest_nr = 100;
foreach (int i in validEntries)
{
if (i < lowest_nr)
lowest_nr = i
if (i > highest_nr)
highest_nr = i;
Console.WriteLine(i);
}
Console.WriteLine("Highest number = " + highest_nr.ToString());
Console.WriteLine("Lowest number = " + lowest_nr.ToString());
validEntries.Max() and validEntries.Min() will get you your highest and lowest values, respectively.
Console.WriteLine("Your valid entries were: ");
foreach (int i in validEntries)
Console.WriteLine(i);
Console.WriteLine();
Console.WriteLine("Your invalid entries were: ");
foreach (string s in invalidEntries)
Console.WriteLine(s);
Would be written (I replaced your foreach):
Console.WriteLine("Your valid entries were: ");
Console.WriteLine(string.Join(Environment.NewLine, validEntries));
Console.WriteLine();
Console.WriteLine("Your invalid entries were: ");
Console.WriteLine(string.Join(Environment.NewLine, invalidEntries));
Console.WriteLine();
Console.WriteLine("Min:{0} Max:{1}",validEntries.Min(),validEntries.Max());

Categories