How to count digits of number without loop? - c#

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).

Related

How to count users answers in Console

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

What is wrong with my while statement? Else statement won't write

Everything runs correctly except the else statement. It gets skipped over once the numbers are equal to each other. It doesn't say "You got it" at the end.
//declare variables
int number = 4;
int guessCount = 0;
int guess;
//get first number
Console.WriteLine("Guess a number between 1 and 10:");
guess = Convert.ToInt32(Console.ReadLine());
guessCount = guessCount + 1; //increment counter
while (guess != number) //keep repeating until number is chosen
{
guessCount = guessCount + 1; //increment counter
if (guess < number) //if statement if guess is less than number
{
Console.WriteLine("Your guess is too low.");
}
else if (guess > number) //if statement if guess is more than number
{
Console.WriteLine("Your guess is too high.");
}
else //
{
Console.WriteLine("You got it!!");
}
//end of while to ask for a new guess
Console.WriteLine("Guess again: ");
guess = Convert.ToInt32(Console.ReadLine());
}
//display output
Console.WriteLine("You figured it out in " + guessCount + " guesses.");
Console.ReadLine(); //keep window open
Your while expression states: guess != number which is true as long as the user does not type in 4 (your hardcoded value). You are setting guess right before the while expression gets checked, so if the user types in the right number, the while expression will be false and it will be jumped over. I commented your code at the problems' locations.
//declare variables
int number = 4;
int guessCount = 0;
int guess;
//get first number
Console.WriteLine("Guess a number between 1 and 10:");
// Problem A: user types in 4 -> guess becomes equal to number -> while expression gets false -> while body will not be executed
guess = Convert.ToInt32(Console.ReadLine());
while (guess != number) //keep repeating until number is chosen
{
guessCount = guessCount + 1; //increment counter
if (guess < number) //if statement if guess is less than number
{
Console.WriteLine("Your guess is too low.");
}
else if (guess > number) //if statement if guess is more than number
{
Console.WriteLine("Your guess is too high.");
}
else //
{
Console.WriteLine("You got it!!");
}
//end of while to ask for a new guess
Console.WriteLine("Guess again: ");
// Problem B: user types in 4 -> guess becomes equal to number -> while expression gets false -> loop ends
guess = Convert.ToInt32(Console.ReadLine());
}
When it is coming into the while loop, it means that guess is != number and the only state that is possible here is guess < number and guess > number that you have already checked for, and guess = number is meaningless because if the guess is equal to number it doesn't even comes into the while loop. This is why your else statement never executes because the only state that your else statement is checking for is guess == number.

How do I test if the first digit of an integer is a 7?

I have had the user enter an integer. I would like to test to see if the first digit is a 7 or not.
string enteredValue;
int number;
Console.WriteLine("Enter integer: ");
enteredValue = Console.ReadLine();
number = Int.Parse(enteredValue);
The test (to see if the first digit is a 7) can occur before or after I parse the string to an int. If the number is not a 7 have the following occur
Console.WriteLine("First digit was not 7");
Console.WriteLine(nRe-enter number ");
You can test it before you parse the string like below:
if(!string.IsNullOrWhiteSpace(enteredValue)
&& enteredValue[0] == '7')
{
int.TryParse(enteredValue, out number);
}
else
{
Console.WriteLine("First digit was not 7");
Console.WriteLine(nRe-enter number ");
}
if(enteredValue.charAt(0)!='7')
{
Console.WriteLine("First digit was not 7");
Console.WriteLine("nRe-enter number ");
}
As enteredValue is a string and taken from console, may be you need not additional check for null or empty if you use LINQ.
if (enteredValue.FirstOrDefault() == '7')
{
int.TryParse(enteredValue, out number);
}else
{
Console.WriteLine("First digit was not 7");
Console.WriteLine("Re-enter number: ");
}
Well let's split your need first.
First step is to find out the first digit of the integer. For this you can simply do the following
int firstDigit = Math.Abs(number);
while(firstDigit >= 10)
firstDigit /= 10;
and firstDigit will contain what you need
Now check if it is 7 or not with a if condition

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

How can I make my program stop reading user input when no input is given?

I am trying to make a program that calculates some specific data from numbers given by a user.
In this example, my program counts amount of numbers in range (10,103) that are divisible by 2, and amount of numbers that are in range (15,50) divisible by 3 within numbers given by user.
On this stage, my program gives the results, when 10 numbers are given (as I specified it in the loop). How can I make my program stop reading numbers and give the results when user imputs an empty line no matter if he, entered 5 or 100 numbers before?
Here is my code, as it looks for now:
using System;
namespace Program1
{
class MainClass
{
public static void Main (string[] args)
{
int input10_103_div_2 = 0;
int input15_50_div_3 = 0;
for (int i = 0; i < 10; i++)
{
string input = Console.ReadLine ();
double xinput = double.Parse (input);
if (xinput > 10 && xinput <= 103 && (xinput % 2) == 0)
{
input10_103_div_2++;
}
if (xinput > 15 && xinput < 50 && (xinput % 3) == 0)
{
input15_50_div_3++;
}
}
Console.WriteLine ("Amount of numbers in range (10,103) divisible by 2: " + input10_103_div_2);
Console.WriteLine ("Amount of numbers in range (15,50) divisible by 3: " + input15_50_div_3);
}
}
}
instead of for, do:
string input = Console.ReadLine();
while(input != String.Empty)
{
//do things
input = Console.ReadLine();
}
if you're trying to allow any number of inputs. Or
if(input == "")
break;
if you want the for loop
Change your loop to go forever and break out of the loop when the string is empty:
for (;;)
{
string input = Console.ReadLine ();
if (String.IsNullOrEmpty(input))
{
break;
}
// rest of code inside loop goes here
}
If you want to restructure the loop, you can use a do while loop:
string input;
do{
input = Console.ReadLine();
//stuff
} while(!string.IsNullOrEmpty(input));
If you just want to be able to break early:
string input = Console.ReadLine ();
if(string.IsNullOrEmpty(str))
break;
double xinput = double.Parse (input);

Categories