Check the length of integer variable - c#

Is there a way to check a lenth of integer variable, and if is to long just trim it.
I hava a field in database that accepts 3 character, lenth is 3.
So is it possible to do like it's done with string variable
example:
cust_ref = cust_ref.Length > 20 ? cust_ref.Substring(0, 19) : cust_ref;
Thanks!

The easiest answer would be:
//The length would be 3 chars.
public int myint = 111;
myint.ToString().Length;

The following worked a treat for me!
public static int IntLength(int i)
{
if (i < 0)
throw new ArgumentOutOfRangeException();
if (i == 0)
return 1;
return (int)Math.Floor(Math.Log10(i)) + 1;
}
Original Source: http://www.java2s.com/Code/CSharp/Data-Types/Getthedigitlengthofanintvalue.htm

You don't have to convert it to a string to make it shorter, that can be done numerically:
if (num > 999) {
num %= 1000;
}
This will cut of digits from the left, if you want to cut them off from the right:
while (num > 999) {
num /= 10;
}
If the value can be negative, also check:
if (num < -99) {
num = -(-num % 100);
}
or:
while (num < -99) {
num = -(-num / 10);
}

cust_ref = cust_ref.ToString().Length > 20 ? Convert.ToInt32(cust_ref.ToString().Substring(0, 19)) : cust_ref;
or simply use
cust_ref = Convert.ToInt32(Convert.ToString(cust_ref).Substring(0, 19));

Use like this
cust_ref= cust_ref.Tostring().Length > 20 ? Convert.ToInt32(cust_ref.ToString().Substring(0, 19)) : cust_ref;

Nont very clear what you're asking for, but as much as I unerstood you're asking for:
int a = 1234567890;
for some reason you want to make it shorter, like
int b = MakeShorter(a);
//b == 1234 (say)
If so, the easiest solution may be, convert it to string, made what you already implemented and reconvert it back to int.
If this is not what you're asking for, please clarify.

The conversion to the string is ugly way to implement it.
It's require a pure math solution
int CutTheNumber(int number, int maxLen)
{
var maxSize = (int)Math.Pow(10, maxlen);
if(maxSize <= Math.Abs(number))
{
number %= maxSize;
}
return number;
}

Checking length
length = cust_ref.ToString().Length;
Remove extra bits
if (length > need)
{
cust_ref =Convert.ToInt32( cust_ref.ToString().Remove(length -(length- need)));
}

for this u will have to do some simple stuffs.
like
cust_ref = Convert.ToInt32(Convert.ToString(cust_ref).Substring(0, 19));
or u can manually store it in any variable and the

You can try this code. use if else statement to check the validation ..
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace avaragescore
{
class Program
{
static void Main(string[] args)
{
float quiz;
float midterm;
float final;
float avrg=0;
Start:
Console.WriteLine("Please enter the Quize Score here");
quiz = float.Parse(Console.ReadLine());
if(quiz > 100)
{
Console.WriteLine("You have entered wrong score please re-enter");
goto Start;
}
Start1:
Console.WriteLine("Please enter the Midterm Score here");
midterm = float.Parse(Console.ReadLine());
if(midterm > 100)
{
Console.WriteLine("You have entered wrong score please re- enter");
goto Start1;
}
Start3:
Console.WriteLine("Please enter the Final Score here");
final = float.Parse(Console.ReadLine());
if(final > 100)
{
Console.WriteLine("You have entered wrong Score Please re-enter");
goto Start3;
}
avrg = (quiz + midterm + final) / 3;
if(avrg >= 90)
{
Console.WriteLine("Your Score is {0} , You got A grade",avrg);
}
else if (avrg >= 70 && avrg < 90)
{
Console.WriteLine("Your Score is {0} , You got B grade", avrg);
}
else if (avrg >= 50 && avrg < 70)
{
Console.WriteLine("Your Score is {0} , You got C grade", avrg);
}
else if (avrg < 50)
{
Console.WriteLine("Yor Score is {0} , You are fail", avrg);
}
else
{
Console.WriteLine("You enter invalid Score");
}
Console.ReadLine();
}
}
}

Related

Number guessing game: Different message when guess = >100?

I'm creating a little number guessing game for class and I have a question that my prof still hasn't spoken about:
In my if-statements I have different messages telling the player when the guess is < random number, > the random number and == the random number. Now I would like to also print a message when the guess is too far off the random number;
If the random number is 700 and my guess is more than 100 off, how do I put this in the if-statement? I have of course tried guess + >100 but that obviously doesn't work. Do I need a new variable for this?
You can do something like this.
if (Math.Abs(guessedNumber - randomNumber)> 100){
Console.WriteLine("Your number is so far from the random number")
}
Either your guess will be 100 bigger or smaller then your number.
int randomNr = 350;
int guess = 250;
int maxOff = 100;
if (guess - randomNr > maxOff || randomNr - guess > maxOff)
{
//Show message.
}
Always try to include your code when asking a question.
Without having your code, this is a potential solution to your question :
1. Print message telling by how much the guess is off
int diff;
diff = random - guess;
if(diff > 0)
{
Console.WriteLine($"guess is smaller by {diff}");
}
else if(diff < 0)
{
Console.WriteLine($"Guess is greater by {diff}");
}
You can try this
public static int rand = new Random().Next(0, 999);
public static string myNumber;
static void Main(string[] args)
{
Console.WriteLine("Guess the random number");
do
{
myNumber = Console.ReadLine();
IHopeIguessRandomNumber(Convert.ToInt32(myNumber));
}
while (Convert.ToInt32(myNumber) != rand);
}
public static void IHopeIguessRandomNumber(int myGuess)
{
if ( myGuess == rand)
{
Console.WriteLine("You're right! This is the right number");
}
else if (myGuess <= rand - 100)
{
Console.WriteLine("Too Low! Your number is < random");
}
else if ( myGuess < rand)
{
Console.WriteLine("Your number is < random");
}
else if (myGuess >= rand + 100)
{
Console.WriteLine("Too Big! Your number is > random");
}
else if (myGuess > rand)
{
Console.WriteLine("Your number is > random");
}
}
Have a nice day :)
You can use a NESTED IF block like this.
if(guessNum < randomNum)
{
if(guessNum < randomNum - 100)
{
Console.WriteLine("The guessed number is too Low");
}
else
{
Console.WriteLine("The guessed number is Low, but you are close");
}
}
else if(guessNum > randomNum)
{
if(guessNum > randomNum + 100)
{
Console.WriteLine("The guessed number is too High");
}
else
{
Console.WriteLine("The guessed number is High, but you are close");
}
}
I can help you with the exact answer if you add the existing code snippet.

cannot figure out while random number generator game is not working c#

I am programming a game that generates a random number and then has the user try to guess the number when the user inputs a number the program will respond with either too high or too low depending on the number generated.The problem I am having is that the loop will just keep executing and the program will not take another user input if the number is incorrect.I have tried using different types of loops like a do while and for loop but keep getting the same problem I feel as though I am missing something simple or making a simple mistake thanks
string usernumber;
Random rnd = new Random();
int value = rnd.Next(1,50); //generates a random number upto 50
int guess = 0;
Console.WriteLine("please enter a number"); //asks for and takes user input
usernumber = Console.ReadLine();//stores user input
guess = Convert.ToInt32(usernumber);
while (guess != value) //this stands for not equals to
{
//guess = Convert.ToInt32(usernumber);
if (value > guess)
{
Console.WriteLine("too high");
}
else if (value < guess)
{
Console.WriteLine("too low");
}
else if (value == guess)
{
Console.WriteLine("bang on the answer was" + value);
}
else
{
Console.WriteLine("errrrrrrrrr");
}
}
Thread.Sleep(2000); //delays the program closing for a bit
You can use this corrected and refactored to have more explicit variables names.
We add 1 to 50 because the Random.Next last parameter is the upper bound excluded.
We use a do...while loop to have a concise algorithm.
We use int.TryParse to get the int from the user. This method returns false and sets the value to 0 in case of conversion error instead of an exception.
We use Console.ReadKey instead of Thread.Sleep, that is more UX friendly.
var random = new Random();
int numberTarget = random.Next(1, 50 + 1);
int numberUser;
do
{
Console.Write("Please enter a number between 1 and 50: ");
if ( int.TryParse(Console.ReadLine(), out numberUser) )
{
if ( numberUser > numberTarget )
{
Console.WriteLine("Too high, retry.");
}
else
if ( numberUser < numberTarget )
{
Console.WriteLine("Too low, retry.");
}
else
{
Console.WriteLine($"Bang on the answer was {numberTarget}.");
}
}
else
{
Console.WriteLine("You didn't enter a valid number, retry.");
}
}
while ( numberUser != numberTarget );
Console.WriteLine("Press a key to exit.");
Console.ReadKey();
In your while loop, you forgot to make another ReadLine.
while (guess != value) //this stands for not equals to
{
if (value > guess)
{
Console.WriteLine("too high");
guess = Convert.ToInt32(Console.ReadLine());
}
else if (value < guess)
{
Console.WriteLine("too low");
guess = Convert.ToInt32(Console.ReadLine());
}
else if (value == guess)
{
Console.WriteLine("bang on the answer was" + value);
}
else
{
Console.WriteLine("errrrrrrrrr");
}
}

Random number guessing game not working C# [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 3 years ago.
Improve this question
I am trying to get this random number guessing game working. The program runs, but it doesn't give the "you won" message when you enter the correct number, and the hint feature does not give the feed back it is supposed to. Any help appreciated.
using System;
namespace randomNumberGame
{
class Program
{
static void Main(string[] args)
{
Random r = new Random();
var val = r.Next(1, 100);
var guess = 0;
bool correct = false;
var attemptsLeft = 5;
Console.WriteLine("I'm thinking of a number between 1 and 100.");
while (!correct && attemptsLeft >= 1)
{
Console.Write("You have " + attemptsLeft + " lives left. Please enter your Guess: ");
string input = Console.ReadLine();
var message = "";
var difference = val - guess;
if (!int.TryParse(input, out guess))
{
Console.WriteLine("That's not a number.");
continue;
}
if (difference == 0)
{
Console.WriteLine("You have won");
correct = true;
}
else
{
if (Math.Abs(difference) >= 50)
{
message = Math.Sign(difference) == -1 ? "Very High" : "Very Low";
}
else if (Math.Abs(difference) < 50 && Math.Abs(difference) >= 20)
{
message = Math.Sign(difference) == -1 ? "High" : "Low";
}
else if (Math.Abs(difference) < 20 && Math.Abs(difference) >= 10)
{
message = Math.Sign(difference) == -1 ? "Moderatley High" : "Moderately Low";
}
else if (Math.Abs(difference) < 10)
{
message = Math.Sign(difference) == -1 ? "Somewhat High" : "Somewhat Low";
}
else Console.WriteLine("???");
}
attemptsLeft--;
}
}
}
}
"it doesn't give the you won message when you enter the correct number"
Actually, it does! But then the program exits so quickly that you never see it. To solve this, add a line that waits for the user to press a key at the end of your Main method, so you can see the final result:
// Add this as the last line of the main method:
Console.ReadKey();
"the hint feature does not give the feed back it is supposed too"
This is because you never output the hint message! At the end of your while loop, add a line to do so:
// Add this as the last line of the while loop:
Console.WriteLine(message);
These things can be found easily if you simply set a breakpoint in your code (in Vistal Studio, click the left margin next to one of the lines and a red dot will appear (or press F9)). Then you can step through the code using F10 and you can watch the values of local variables change and see what is happening step-by-step.
Another way to help avoid problems (and to narrow down where they occur) is to take out chunks of code that does something specific and put it in a method. This will make it easier to debug in the long run.
For example, we can write methods that take in a string to display to the user as a prompt for input, and return a strongly-typed value based on their entry. We can also have these methods take in an optional validation method that can be used to validate that the input they entered falls within a valid range (like a number from 1 to 100, or a name that's not longer than 25 characters):
public static string GetStringFromUser(string prompt,
Func<string, bool> validator = null)
{
string result;
var cursorTop = Console.CursorTop;
do
{
ClearSpecificLineAndWrite(cursorTop, prompt);
result = Console.ReadLine();
} while (!(validator?.Invoke(result) ?? true));
return result;
}
public static int GetIntFromUser(string prompt,
Func<int, bool> validator = null)
{
int result;
var cursorTop = Console.CursorTop;
do
{
ClearSpecificLineAndWrite(cursorTop, prompt);
} while (!int.TryParse(Console.ReadLine(), out result) ||
!(validator?.Invoke(result) ?? true));
return result;
}
private static void ClearSpecificLineAndWrite(int cursorTop,
string message)
{
Console.SetCursorPosition(0, cursorTop);
Console.Write(new string(' ', Console.WindowWidth));
Console.SetCursorPosition(0, cursorTop);
Console.Write(message);
}
We can also write a helper method to get our "difference string", which could take in the guess, the number, and the min and max values, then calculate a percentage of how close they were and then return the appropriate string:
public static string GetDifferenceString(int guess, int number,
int minVal, int maxVal)
{
var percentAway =
Math.Abs(guess - number) / (double)(maxVal - minVal) * 100;
var direction = guess - number > 0 ? "High" : "Low";
if (percentAway < 10) return $"Very close, but {direction}";
if (percentAway < 20) return $"Just a little {direction}";
if (percentAway < 30) return $"Somewhat {direction}";
if (percentAway < 40) return $"Moderately {direction}";
if (percentAway < 50) return $"{direction}";
return $"Very {direction}";
}
This simplifies our main code by removing the loops and checking results from there, and lets us focus on our main tasks:
static void Main(string[] args)
{
var randomNumber = new Random().Next(1, 101);
var maxAttempts = 5;
var guess = 0;
Console.WriteLine("I'm thinking of a number between 1 and 100.");
for (int attempt = 0; attempt < maxAttempts; attempt++)
{
Console.WriteLine($"You have {maxAttempts - attempt} " +
$"out of {maxAttempts} attempts remaining.");
guess = GetIntFromUser("Please enter your guess (1 - 100): ",
i => i > 0 && i < 101);
if (guess == randomNumber)
{
Console.WriteLine($"You have won in {attempt + 1} tries!");
break;
}
Console.WriteLine(GetDifferenceString(guess, randomNumber, 1, 100));
}
if (guess != randomNumber)
{
Console.WriteLine("Sorry, you lose! The number was: " +
$"{randomNumber}");
}
GetKeyFromUser("\nDone! Press any key to exit...");
}

c# Filter int for specific parameter

Is there any more "elegant" way to filter a number input for specific parameters?
Like here, I need to say different things if you're to high, to low or of the limits.
Would appreciate if you explain what you suggest. I'm like 2 weeks into programming.
//VARIABLES
int userNumber;//uN
int searchedNumber;//sN
//NUMBER WE'RE LOOKING FOR
searchedNumber = 87;
//TASK FOR "CUSTOMER"
Console.WriteLine("Type in a number between 1-100!");
//DO-WHILE, because it hast to run one either way
do
{
//READING OUT CONSOLE
string userNumberString = Console.ReadLine();
//CONVERTING STRING TO INT
userNumber = int.Parse(userNumberString);
//uN > THAN sN BUT <= 100
if (userNumber > searchedNumber && userNumber <= 100)
{
Console.WriteLine("To High! /n Try again.");
}
//uN < THAN sN BUT >= 1
else if (userNumber < searchedNumber && userNumber >= 1)
{
Console.WriteLine("To Low! /n Try again.");
}
//uN >= 101 AND uN <= 0
else if (userNumber >= 101 || userNumber <= 0)
{
Console.WriteLine("Between 1 and 100, Dummy!");
}
else
{
//IF NOTHING IS TRUE uN=sN
Console.WriteLine("JACKPOT!");
}
//LOOPING CONDITION
} while (userNumber != searchedNumber);
If this q is already answered somewhere, i'm sorry. English is not my native language and i struggled to even find the right search term.
I suggest extracting methods, please, do not cram everything into huge single routine:
public static int ReadInteger(string title) {
if (!string.ISNullOrWhiteSpace(title))
Console.WriteLine(title);
while (true) {
if (int.TryParse(Console.ReadLine(), out int result))
return result;
Console.WriteLine("This is not a valid integer! Try again.");
}
}
public static string FeedBack(int user, int actual) {
if (user < 0 || user > 100)
return "Between 1 and 100, Dummy!"
else if (user < actual)
return "Too Low! /n Try again.";
else if (user > actual)
return "Too High! /n Try again.";
else
return "JACKPOT!"
}
Then use these methods in a tiny loop:
int userNumber = 0;
int searchedNumber = 87;
do {
userNumber = ReadInteger("Type in a number between 1-100!");
Console.WriteLine(FeedBack(userNumber, actual));
}
while (userNumber != searchedNumber);
One way to get rid of all the else statements is to move the code to a method and return from the method as soon as you know what the response should be.
Something like this
public string EvaluateNumber(int userNumber, int searchedNumber)
{
if (searchedNumber <= 0 || searchedNumber >= 101)
return "Between 1 and 100, Dummy!";
if (searchedNumber < userNumber)
return "Too low! /n Try again.";
if (searchedNumber > userNumber)
return "Too high! /n Try again.";
return "JACKPOT!"; // If we get to here, the numbers are equal
}
This code can get little bit cleaner by rearramging conditions - if will get a lot simplier :) Also, if you have one line under if, you can omit curly braces, see below code. I also included some comments, which I hope, wil be useful:
do
{
//READING OUT CONSOLE
string userNumberString = Console.ReadLine();
//CONVERTING STRING TO INT
// here you need to be careful, what if user types "a"?
// I suggest reading about int.TryParse :)
userNumber = int.Parse(userNumberString);
//uN >= 101 AND uN <= 0
if (userNumber >= 101 || userNumber <= 0)
Console.WriteLine("Between 1 and 100, Dummy!");
// now we are sure we are in the range
if (userNumber > searchedNumber)
Console.WriteLine("To High! /n Try again.");
else if (userNumber < searchedNumber)
Console.WriteLine("To Low! /n Try again.");
else
//IF NOTHING IS TRUE uN=sN
Console.WriteLine("JACKPOT!");
//LOOPING CONDITION
} while (userNumber != searchedNumber);
Thinking of a cleaner code:
public static void Main()
{
//VARIABLES
int userNumber;//uN
int searchedNumber = 87;
int min = 1;
int max = 100;
//TASK FOR "CUSTOMER"
Console.WriteLine($"Type in a number between {min}-{max}!");
//DO-WHILE, because it hast to run one either way
do
{
//READING OUT CONSOLE
string userNumberString = Console.ReadLine();
//CONVERTING STRING TO INT
if (int.TryParse(userNumberString, out userNumber))
{
if (userNumber >= min && userNumber <= max)
{
if (userNumber == searchedNumber)
{
Console.WriteLine("JACKPOT!");
}
else
{
Console.WriteLine("To " + (userNumber < searchedNumber ? "Low" : "High") + "! Try again.");
}
}
else
{
Console.WriteLine($"Between {min} and {max}, Dummy!");
}
}
else
{
Console.WriteLine($"One integer number, Dummy!");
}
} while (userNumber != searchedNumber);
}
The TryParse it's very important

C# factorial calculator is not working right

My factorial calculator isn't working quite correctly.
It works as expected from 1 to 20, as my professor wants. However, entering 0 should return a factorial of 1; it returns 0
Here is my code:
private void CalculateFactorial(long number)
{
//perform the calculations
long result = number;
for (int i = 1; i < number; i++)
{
result = result * i;
}
//display the calculated Factorial to the user
txt_Factorial.Text = result.ToString("n0");
}
Here is the method which calls the above method, the event handler for the calculate button:
private void btn_Calculate_Click(object sender, EventArgs e)
{
//get the users input
long number = long.Parse(txt_Number.Text);
// make sure the number not invalid. If it is invalid, tell the user
// otherwise, proceed to calculation.
if (number < 0 || number > 20)
txt_Factorial.Text = "Invalid Number";
else
CalculateFactorial(number);
txt_Number.Focus(); // returns the focus to the number box whether or not data was valid
Ideas?
If you step through this in a debugger the problem becomes pretty clear. And as you're just getting started with programming I highly recommend getting used to a debugger as early as you can. It's an absolutely invaluable tool for programming.
Look at your for loop:
for (int i = 1; i < number; i++)
What happens when number is 0? The loop never runs. You can't include 0 in the loop range because that would set every result to 0 by first multiplying it by 0. So you need to add an explicit check for 0 in the function logic:
if (number == 0)
return 1;
// continue with your loop here
Factorial of 0 is 1 by definition, not by calculation, and your code does not reflect that. Add a check before your code:
if (number == 0)
result = 1;
else
// compute factorial
Also think about creating a function that returns an integer value as the result.
You can use this :
if(number == 0){
result = 1;
}
for (int i = 1; i <= number; i++)
result *= i;
}
also your formula is wrong because n! = 1*2*3*.....*n
You can test the following code! tested and works. Recursive Implementation as well as basic implementation
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApplication50
{
class Program
{
static void Main(string[] args)
{
NumberManipulator manipulator = new NumberManipulator();
Console.WriteLine("Please Enter Factorial Number:");
int a= Convert.ToInt32(Console.ReadLine());
Console.WriteLine("---Basic Calling--");
Console.WriteLine("Factorial of {0} is: {1}" ,a, manipulator.factorial(a));
Console.WriteLine("--Recursively Calling--");
Console.WriteLine("Factorial of {0} is: {1}", a, manipulator.recursively(a));
Console.ReadLine();
}
}
class NumberManipulator
{
public int factorial(int num)
{
int result=1;
int b = 1;
do
{
result = result * b;
Console.WriteLine(result);
b++;
} while (num >= b);
return result;
}
public int recursively(int num)
{
if (num <= 1)
{
return 1;
}
else
{
return recursively(num - 1) * num;
}
}
}
}

Categories