C# string to array from readline issue - c#

I am doing some C# exercises, the assignment is to check if att Swedish SSN is issued to a woman or a man.
The algorithm checks if the ninth number is equally dividable by 0, then it's a woman or else a man.
If I use a hardcoded "nr" in a string variable, the algorithm works, but if I try to read it from a readline statement, I get the following error:
Index was out of range. Must be non-negative and less than the size of the collection. Parameter name: startIndex
This is the code I am using:
//string personnr = "860215-2097";
string personnr = "";
char[] arr;
public void CheckGender(string pnr)
{
arr = personnr.ToCharArray(9, 1);
if (personnr[9] %2 == 0)
{
Console.WriteLine($"Woman!!!");
}
else
{
Console.WriteLine($"Man!!!");
}
}
public void PrintPersonNr()
{
Console.WriteLine("Write a personnr in the format yymmdd-nnnn: ");
string nr = Console.ReadLine();
CheckGender(nr);
}
So it's my PrintPersonNr method that's not working properly I guess..

You can try this:
public enum SSNGender
{
Female,
Male
}
class Program
{
static public Dictionary<SSNGender, string> SSNGenderText
= new Dictionary<SSNGender, string>()
{
{ SSNGender.Female, "Woman" },
{ SSNGender.Male, "Man" },
};
static public SSNGender CheckSSNGender(string pnr)
{
// Here check the validity of the pnr (length, format...)
return pnr[9] % 2 == 0 ? SSNGender.Female : SSNGender.Male;
}
static void Main(string[] args)
{
Console.WriteLine("Write a personnr in the format yymmdd-nnnn: ");
string nr = Console.ReadLine();
var result = CheckSSNGender(nr);
Console.WriteLine(SSNGenderText[result]);
Console.ReadKey();
}

Try following :
public void CheckGender(string pnr)
{
string arr = pnr.Substring(10, 1);
if (arr == "0")
{
Console.WriteLine("Woman!!!");
}
else
{
Console.WriteLine("Man!!!");
}
}

What you need to do is to use the modulus operator and then to check if this number is then divisible by two and if the result is zero then it is even.
There is a fundamental issue as well, you would need to check if the character is a number or not. if it is then the operation would need to then be completed, if not you need to let the user know.
I have modified JDWeng post
public void CheckGender(string pnr)
{
string arr = pnr.Substring(9, 1);
int num =0;
if (int.TryParse(arr, num))
{
if ((num % 2) == "0")
{
Console.WriteLine("Man!!!");
}
else
{
Console.WriteLine("Woman!!!");
}
}
else
{
Console.WriteLine("Not a number!");
}
}
Best of luck in your exercise as well!!!

Related

How to determine input when the can have a variable?

I'm working on this commandline based dice. And I want it to be able to output statistics and reset those internal statistics. Currently I have the following classes: Dice and DiceInterface.
I want the user to be able to use the following format for input: "'Throw' to throw the dice, alternate use 'Throw(x)', 'Stat(side)' to see how many times (side) has been thrown, or 'Reset' to reset thrown statistics"
I need a way to determine if the user has typed Throw, Throw(x), Stat(side) or Reset. Throw and Reset are obvious to me but I find it quite difficult to imagine a way to do Throw(x) and Stat(side). Does anyone have any tips or a solution?
Thanks in advance!
using System;
using System.Collections.Generic;
using System.Text;
namespace Oefening_2
{
class DiceInterface
{
static void Main()
{
StartProgram();
}
static void StartProgram()
{
Console.WriteLine("Hello, how many sides would you like the dice to have?");
var input = Console.ReadLine();
if (Int32.TryParse(input, out int number))
{
int desiredSides = number;
Dice NewDice = new Dice(desiredSides);
Console.WriteLine("What would you like to do? ");
Console.WriteLine("Type: 'Throw' to throw the dice, alternate use 'Throw(x)', 'Stat(side)' to see how many times (side) has been thrown, or 'Reset' to reset thrown statistics");
MainIO(NewDice);
}
else
{
Console.WriteLine("That is not an integer! The program will restart now...");
StartProgram();
}
}
static void MainIO(Dice CurrentDice)
{
Console.Write("Input: ");
string input = Console.ReadLine();
//Throw
if (input == "Throw")
{
Console.WriteLine(CurrentDice.Throw());
MainIO(CurrentDice);
}
//Throw(x)
else if(input == "")
//Thrown(side)
//Reset
else if (input == "Reset")
{
CurrentDice.ResetStatistics();
MainIO(CurrentDice);
}
}
}
}
using System;
namespace Oefening_2
{
class Dice
{
public int Sides { get; set; }
private readonly Random _rnd = new Random();
public int[] Thrown;
public Dice(int sides)
{
Sides = sides;
Thrown = new int[sides--];
}
public Dice():this(6)
{
}
public int Throw()
{
int thrownNumber = _rnd.Next(1, Sides);
Thrown[thrownNumber]++;
return thrownNumber;
}
public int NrOfTimesThrown(int side)
{
int result;
result = Thrown[side];
return result;
}
public void ResetStatistics()
{
for(int i = 0 ; i < Sides; i++)
{
Thrown[i] = 0;
}
}
}
}
This can be fairly simply done with StartsWith to check if a string starts with some prefix, and use .Remove to get anything after this prefix:
if(input.StartsWith("Stat"){
var parameterString = input.Remove(0, "Stat".Length);
if(int.TryParse(parameterString , out var side){
...
}
}
If I correctly understood your problem, it could be solved with an approach like this:
Console.WriteLine("Enter a value");
var s = Console.ReadLine();
if(s.Contains('('))
{
int pFrom = s.IndexOf("(");
int pTo = s.LastIndexOf(")");
var myChoice = s.Substring(0, pFrom);
var myValue = s.Substring(pFrom + 1, pTo - pFrom);
Console.WriteLine($"You choosed : {myChoice}");
Console.WriteLine($"With a value of: {myValue}");
}
This is just a brief example of how to "understand" if there is a value and then recover it.
I hope this could help you somehow.

methods program not working of guessing a number

I'm having issues creating a program that is a number guessing program. I think I have the written part right but possibly not the order of it? I have to use multiple methods such as a method for number generator of the number that is supposed to be guessed, a method for collecting the guess input, and method for checking the guess to see if it's right. I've literally have tried just about everything for days but all I get is rather a repeat of, "Enter the number: " even if its right, although it's supposed to repeat if it's too high or low. Or sometimes the console won't print anything. what is wrong? Here is the code:
using System;
namespace GuessTheNumber
{
class Program
{
public static int RandomNumberGenerator()
{
Random random = new Random();
return random.Next(1, 21);
}
public static int InputGetter()
{
Console.Write("Enter in a number: ");
int guess = Convert.ToInt32(Console.ReadLine());
return guess;
}
public static String GuessChecker(int guess, int secretNumber)
{
if(guess > secretNumber)
{
return "Too high!";
}
else if (guess < secretNumber)
{
return "Too low!";
}
else
{
return "Correct";
}
}
static void Main(string[] args)
{
int secretNumber = 10;
Console.WriteLine("" + secretNumber);
while (true)
{
while (InputGetter() != secretNumber)
{
InputGetter();
GuessChecker(InputGetter(), secretNumber);
}
if (GuessChecker(InputGetter(), secretNumber) == ("Correct!"))
{
Console.WriteLine("Would you like to play again?");
String input = Console.ReadLine();
if (GuessChecker(InputGetter(), secretNumber) == ("Yes"))
{
secretNumber = RandomNumberGenerator();
}
else if (GuessChecker(InputGetter(), secretNumber) == ("No"))
{
break;
}
}
}
}
}
}
You are invoking InputGetter() multiple times and your logic is incorrect.
It has nothing to do with Random instance being used.
I have quickly modified your code and it should work now as follows:
New number is generated, if you enter low/high message is displayed, if you enter correct number you are presented with the Would you like to try again message.
EDIT: I did not want to change original code much,In general Comparing strings is bad, you should not use it. Creating enum like and comparing would be much better
class Program
{
public static int RandomNumberGenerator()
{
Random random = new Random();
var generatedNumber = random.Next(1, 21);
Console.WriteLine($"New Number generated! {generatedNumber}");
return generatedNumber;
}
public static int InputGetter()
{
Console.Write("Enter in a number: ");
int guess = Convert.ToInt32(Console.ReadLine());
return guess;
}
public static String GuessChecker(int guess, int secretNumber)
{
if (guess > secretNumber)
{
Console.WriteLine("Too High");
return "Too high!";
}
else if (guess < secretNumber)
{
Console.WriteLine("Too low!");
return "Too low!";
}
else
{
Console.WriteLine("Correct");
return "Correct";
}
}
static void Main(string[] args)
{
int secretNumber = 10;
Console.WriteLine("" + secretNumber);
while (true)
{
int enteredNumber = 0;
do
{
enteredNumber = InputGetter();
} while (GuessChecker(enteredNumber, secretNumber)!="Correct");
Console.WriteLine("Would you like to play again?[Yes/No]");
String input = Console.ReadLine();
if (input=="Yes")
{
secretNumber = RandomNumberGenerator();
}
else
{
break;
}
}
}
}

How do I search an int array vs a string array by comparing it to user input

How do I check if user input matches a number in an array?
I've learned to compare user input or search using a string array, however doing the same with an int array is not working for me.
zipCode[i] = 0;
int userZip = 0;
do
{
Console.WriteLine( "enter a 5 digit zip code to see if it is supported in our area." );
Console.WriteLine( );
Console.WriteLine( "Enter a 0 to exit the program" );
userZip = 0;
if ( userZip == zipCode[i] )
{
found = true;
if ( found )
{
Console.WriteLine( "We support zip code {0}", userZip ); ;
}
else
{
Console.WriteLine( "We do not support", userZip );
}
}
} while ( userZip != 0 );
Console.ReadLine( );
How do I check if user input matches a number in an array?
using System;
using System.Collections.Generic;
public class Program
{
static List<string> _zipCodes;
static Program()
{
_zipCodes = new List<string>() { "80205", "80225", "80210" };
}
static void Main(string[] args)
{
string userZip = string.Empty;
do
{
Console.WriteLine("enter a 5 digit zip code to see if it is supported in our area.");
Console.WriteLine();
Console.WriteLine("Enter a -1 to exit the program");
userZip = Console.ReadLine();
if (_zipCodes.Contains(userZip))//<---------------THAT WAY
{
Console.WriteLine("We support zip code {0}", userZip); ;
}
else
{
Console.WriteLine("We do not support zip code {0}", userZip);
}
} while (userZip != "-1");
}
}
How do I check if user input matches a number in an array?
I will answer this question, though I can't post an example using your sample code since it's incomplete and it's not exactly clear what it's supposed to do.
First, let's create a method that gets an integer from the user. This method will continually loop until the user enters a valid integer:
public static int GetIntFromUser(string prompt = null)
{
int input;
int row = Console.CursorTop;
int promptLength = prompt?.Length ?? 0;
do
{
Console.SetCursorPosition(0, row);
Console.Write(prompt + new string(' ', Console.WindowWidth - promptLength - 1));
Console.CursorLeft = promptLength;
} while (!int.TryParse(Console.ReadLine(), out input));
return input;
}
Now, we can use that method to get the zip code from the user:
int userZipCode = GetIntFromUser("Enter a 5 digit zip code to see if it's supported: ");
Now I'm assuming you have an array of zip codes that are supported. Perhaps something like:
private static int[] GetSeattleZipCodes()
{
return new []
{
98101, 98102, 98103, 98104, 98105, 98106, 98107, 98108, 98109, 98110,
98111, 98112, 98113, 98114, 98115, 98116, 98117, 98118, 98119, 98121,
98122, 98124, 98125, 98126, 98127, 98129, 98131, 98133, 98134, 98136,
98138, 98139, 98141, 98144, 98145, 98146, 98148, 98154, 98155, 98158,
98160, 98161, 98164, 98165, 98166, 98168, 98170, 98174, 98175, 98177,
98178, 98181, 98185, 98188, 98190, 98191, 98194, 98195, 98198, 98199
};
}
So, now we have an int user input, and an int[] of valid zip codes, so to see if the array of valid zip codes contains the user zip code, we can just use the Contains method:
int[] seattleZipCodes = GetSeattleZipCodes();
bool found = seattleZipCodes.Contains(userZipCode);
TheFastCat beat me, but:
using System;
using System.Collections.Generic;
namespace ConsoleApplication1
{
class Program
{
private static IEnumerable<string> zipCodes = new string[] { "90210", "94102", "98101", "80014" };
static void Main(string[] args)
{
Console.WriteLine("enter a 5 digit zip code to see if it is supported in our area, or '0' to exit");
do {
// Read next line
string userZip = Console.ReadLine().Trim();
// Exit program?
if (userZip == "0")
break;
// Validate input
if (userZip.Length != 5)
{
Console.WriteLine("ERROR: Zip code {0} is {1} characters; expected 5", userZip, userZip.Length);
continue;
}
int n;
bool isNumeric = int.TryParse(userZip, out n);
if (!isNumeric)
{
Console.WriteLine("ERROR: Zip code {0} must be numeric", userZip);
continue;
}
// Finally, see if our zip code matches a zip code in the list
bool found = zipCodes.Contains(userZip);
if (found)
{
Console.WriteLine("We support zip code {0}", userZip); ;
}
else
{
Console.WriteLine("We do not support " + userZip);
}
} while (true);
Console.WriteLine("Done: exiting program");
}
}
}
Note:
Initializing the list
Validating the input
Using IEnumerable.Contains() ... without necessarily messing with LINQ.
Use of "break" and "continue" to control the loop, without necessarily needing an extraneous variable.
An int array is Enumerable<int>, so you could just use Contains(): https://learn.microsoft.com/en-us/dotnet/api/system.linq.enumerable.contains?view=netframework-4.7.2
TheFastCat and Rufus L done great job.
I just want to add an example. Using 'var' datatypes makes things easy and durable as well in C#
This example demonstrates both 'int' and 'string' using var datatypes in both cases. Good luck haberjin.
static void Main(string[] args)
{
//var ZipCodes = new List<string>() { "04846", "40569", "76859","54896", "84623" }; // ZipCodes are stored as a string in a List
var ZipCodes = new List<int>() { 04846, 40569, 76859, 54896, 84623 }; // ZipCodes are stored as an int in a List
//var userZip = "";
var userZip = 0;
do
{
Console.WriteLine("Enter a 5 digit zip code to see if it is supported in our area.");
//userZip = Console.ReadLine(); // Enable to receive userZip as a string
userZip = int.Parse(Console.ReadLine()); // receive userZip as an int
if (ZipCodes.Contains(userZip))
{
Console.WriteLine("We support zip code {0}", userZip);
}
else
{
Console.WriteLine("We do not support", userZip);
}
//} while (userZip != "0");
} while (userZip != 0);
}

In C#, How can I determine if a given string is a palindrome or not? [duplicate]

This question already has answers here:
Check if a string is a palindrome
(33 answers)
Closed 6 years ago.
I'm currently wondering if when a given string (word), how can I determine if it is a palindrome or not. A palindrome is a word or phrase that is the same if read forward or backward. I think I can solve this by looping through the half the word and comparing each letter with the other half. An example for this could be: (word[0] == word[word.Length-1-0]) would compare the first letter with the last letter of word, and (word[1] == word[word.Length-1-1]) would compare the second letter with the second to last letter.
Example Input could be: racecar
Example Output: True
Am I approaching this problem correctly towards the proper solution?
Here's a bit of I've written down so far.
public bool Test6(string word)
{
for (int i = 0; i < word.Length; i++)
{
if (word[0] == word[word.Length - 1 - 0])
{
}
I would do this (quickly).
string input = "..."
string reverse = new string(input.ToCharArray().Reverse().ToArray());
if(input.Equals(reverse)
{
// polindrome.
}
Please follow this link http://www.dotnetperls.com/palindrome
You can do it using this example without using any built in method :
using System;
class Program
{
public static bool IsPalindrome(string value)
{
int min = 0;
int max = value.Length - 1;
while (true)
{
if (min > max)
{
return true;
}
char a = value[min];
char b = value[max];
if (char.ToLower(a) != char.ToLower(b))
{
return false;
}
min++;
max--;
}
}
static void Main()
{
string[] array =
{
"civic",
"deified",
"deleveled",
"devoved",
"dewed",
"Hannah",
"kayak",
"level",
"madam",
"racecar",
"radar",
"redder",
"refer",
"repaper",
"reviver",
"rotator",
"rotor",
"sagas",
"solos",
"sexes",
"stats",
"tenet",
"Dot",
"Net",
"Perls",
"Is",
"Not",
"A",
"Palindrome",
""
};
foreach (string value in array)
{
Console.WriteLine("{0} = {1}", value, IsPalindrome(value));
}
}
}
A shorter version using LINQ would be
bool IsPalindrome(string x)
{
return Enumerable.Range(0,x.Length/2).All(e => x[e] == x[x.Length-1-e]);
}
Please find the code below
using System;
using System.Linq;
class MyClass
{
static void Main(string[] args) {
string str = Console.ReadLine();
string backwardsGuy = new string(str.Reverse().ToArray());
if(str==backwardsGuy)
{
Console.WriteLine("True");
}
else
{
Console.WriteLine("False");
}
}
}
Sample code-
static void Main(string[] args)
{
string s,revs="";
Console.WriteLine(" Enter string");
s = Console.ReadLine();
for (int i = s.Length-1; i >=0; i--) //String Reverse
{
revs += s[i].ToString();
}
if (revs == s) // Checking whether string is palindrome or not
{
Console.WriteLine("String is Palindrome \n Entered String Was {0} and reverse string is {1}", s, revs);
}
else
{
Console.WriteLine("String is not Palindrome \n Entered String Was {0} and reverse string is {1}", s, revs);
}
Console.ReadKey();
}

Adding a Form to an existing console application?

I need to add a form to my existing application i have it all laid out but how do I get it to use the code from the form as to make it seamless. Any thoughts? and sorry for the wall of code just thought it might help.
The Validate button should get its info from the console like below
The Generate action should append the check digit like in this example
public static void Main(string[] args)
{
Console.Write("Enter a valid 10 digit ISBN Number ");
string isbn = isbnChecker.DestabilizeIsbn(Console.ReadLine()); // Normalizes the input and puts it on string "str"
if (isbn.Length > 10 || isbn.Length < 9) // If the string length is greather than 10, or smaller than 9
{
Console.WriteLine("The number you have entered is not a valid ISBN try again."); // Print invalid number
Console.ReadLine();
}
else if (isbn.Length == 10) // If the length is 10
{
if (isbnChecker.CheckNumber(isbn)) // If function CheckNum return "true"...
Console.WriteLine("The number you have entered is a valid ISBN");
else // If it returns "false"...
Console.WriteLine("The number you have entered is not a valid ISBN try again.");
Console.ReadLine();
}
else // Else (If the number is NOT greater than 10 or smaller than 9, NOR is it 10 -> If the number is 9)
{
Console.WriteLine("The Check digit that corresponds to this ISBN number is " + checkIsbnClass.CheckIsbn(isbn) + "."); // Print the checksum digit
Console.ReadLine();
}
}
public static class isbnChecker
{
public static bool CheckNumber(string isbn) // Checks if the checksum digit is correct
{
if (isbn[9].ToString() == checkIsbnClass.CheckIsbn(isbn)) // If the 10th digit of the number is the same as the calculated digit...
return true;
else // If they're not the same...
return false;
}
public static string DestabilizeIsbn(string isbn) // replace the string
{
return isbn.Replace("-", "").Replace(" ", "");
}
}
public static string CheckIsbn(string isbn) // Calculates the 10th digit of a 9-digits partial ISBN number
{
int sum = 0;
for (int i = 0; i < 9; i++) // For each number...
{
sum += int.Parse(isbn[i].ToString()) * (i + 1); // ...Multiply the number by it's location in the string
}
if ((sum % 11) == 10) // If the remainder equals to 10...
{
return "x"; // Output X
}
else // If it does not equal to 10...
{
return (sum % 11).ToString(); // Output the number
}
}
public static bool CheckNumber(string isbn) // Checks if the checksum digit is correct
{
if (isbn[9].ToString() == CheckIsbn(isbn)) // If the 10th digit of the number is the same as the calculated digit...
return true;
else // If they're not the same...
return false;
}
public static string DestabilizeIsbn(string isbn) // replace the string
{
return isbn.Replace("-", "").Replace(" ", "");
}
}
public partial class IsbnForm : Form
{
public IsbnForm()
{
InitializeComponent();
}
private void textBox1_TextChanged(object sender, EventArgs e)
{
this.xInputTextBox.Text = "Enter a Valid ISBN";
}
}
}
I'm not sure what you're asking here. If you want the user to enter the ISBN in the form, then you'd do this:
using (var frm = new IsbnForm())
{
var rslt = frm.ShowDialog();
if (rslt == DialogResult.OK)
{
// Access property that gets the value the user entered.
}
else
{
// User canceled the form somehow, so show an error.
}
}
If you want to display the form and have the entry field displaying the ISBN that the user entered on the command line, then you'll need to add a property or method to the IsbnForm class so that you can set the value before displaying the form. That is, inside IsbnForm, add this property:
public string Isbn
{
get { return xInputTextBox.Text; }
set { xInputTextBox.Text = value; }
}
And then, to populate it:
Console.Write("Enter an ISBN: ");
var isbn = Console.ReadLine();
using (var frm = new IsbnForm())
{
frm.Isbn = isbn; // populates the field in the form.
var rslt = frm.ShowDialog();
// etc, etc.
}

Categories