C# Ask user another input - c#

I am creating a soundDex application and I need to ask the user for a second name after they have inputted the first one. I also want "error no input" if the user does not input a second name. How would I do this within my soundDex?
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SoundDexFinal
{
class Program
{
static void Main(string[] args)
{
string input = null;
bool good = false;
Console.WriteLine("SoundDex is a phonetic algorithm which allows a user to encode words which sound the same into digits."
+ "The program allows the user essentially to enter two names and get an encoded value.");
while (!good) // while the boolean is true
{
Console.WriteLine("Please enter a name -> "); // asks user for an input
input = Console.ReadLine();
// Make sure the user entered something
good = !string.IsNullOrEmpty(input); // if user enters a string which is null or empty
if (!good) // if boolean is true
Console.WriteLine("Error! No input."); // displays an error to the user
}
soundex soundex = new soundex(); // sets new instance variable and assigns from the method
Console.WriteLine(soundex.GetSoundex(input)); // gets the method prior to whatever the user enters
Console.ReadLine(); // reads the users input
}
class soundex
{
public string GetSoundex(string value)
{
value = value.ToUpper(); // capitalises the string
StringBuilder soundex = new StringBuilder(); // Stringbuilder holds the soundex code or digits
foreach (char ch in value) // gets the individual chars via a foreach which loops through the chars
{
if (char.IsLetter(ch))
AddChar(soundex, ch); // When a letter is found this will then add a char
} // soundex in (parameter) is for adding the soundex code or digits
return soundex.ToString(); //return the value which is then converted into a .String()
}
private void AddChar(StringBuilder soundex, char character) //encodes letter as soundex char and this then gets appended to the code
{
string code = GetSoundexValue(character);
if (soundex.Length == 0 || code != soundex[soundex.Length - 1].ToString())
soundex.Append(code);
}
private string GetSoundexValue(char ch)
{
string chString = ch.ToString();
if ("BFPV".Contains(chString)) // converts this string into a value returned as '1'
return "1";
else if ("CGJKQSXZ".Contains(chString)) // converts this string into a value returned as '2'
return "2";
else if ("DT".Contains(chString)) // converts this string into a value returned as '3'
return "3";
else if ("L".Contains(chString)) // converts this string into a value returned as '4'
return "4";
else if ("MN".Contains(chString)) // converts this string into a value returned as '5'
return "5";
else if ("R".Contains(chString)) // converts this string into a value returned as '6'
return "6";
else
return ""; // if it can't do any of these conversions then return nothing
}
}
}
}

I admit, I am not entirely clear on what part precisely you're having trouble with. But the specific goal is stated clearly enough, and you've provided a sufficient code example, so…
The basic problem is "how do I require the user to input the same kind of data more than once?" The basic answer is the same as for any programming problem that involves having to repeat an action: generalize that action into a subroutine (i.e. "method" in C# parlance) that will perform that action, and call the subroutine every time you need to perform the action.
For example:
class Program
{
static void Main(string[] args)
{
string input1, input2;
Console.WriteLine("SoundDex is a phonetic algorithm which allows a user to encode words which sound the same into digits."
+ "The program allows the user essentially to enter two names and get an encoded value.");
input1 = GetValidInput("Please enter a name -> ");
input2 = GetValidInput("Please enter a second name -> ");
soundex soundex = new soundex(); // sets new instance variable and assigns from the method
Console.WriteLine(soundex.GetSoundex(input1)); // gets the method prior to whatever the user enters
// do whatever you want with input2 as well
Console.ReadLine(); // reads the users input
}
static string GetValidInput(string prompt)
{
while (true)
{
string input;
Console.WriteLine(prompt); // asks user for an input
input = Console.ReadLine();
// Make sure the user entered something
if (!string.IsNullOrEmpty(input))
{
return input;
}
Console.WriteLine("Error! No input."); // displays an error to the user
}
}
}

Related

Trying to convert from hexadecimal to decimal and binary but shows an error if i input letter after f

I created this code in c# to convert a hexadecimal number entered by the user to decimal and binary which the code does but I want the code to run so that if the user enters a letter that is not between a-f, a message box shows up with a message telling the user their input is invalid but instead of doing this, the code gives me an error. Can anyone help me out?
bool valid = false;
string hexadecimalnum = HexadecimalTxt.Text;
Checking if the number inputed by the user is in between 0-9 and a-f (lowercase or uppercase)
if(Regex.IsMatch(hexadecimalnum, "\[^-9A-F\]+$") || Regex.IsMatch(hexadecimalnum, "\[^-9a- f\]+$"))
{
// if the hex value is in between 0-9 and a-f then the condition is true
valid = true;
}
since the condition is true convert the hex number to binary and decimal
if(valid)
{
DecimalTxt.Text = Convert.ToInt32(hexadecimalnum, 16).ToString();
int temp = Convert.ToInt32(hexadecimalnum, 16);
BinaryTxt.Text = Convert.ToString(temp, 2);
}
// the condition is not true so print out a invalid number message
else
{
MessageBox.Show("Invalid - please enter a hexadecimal value in this box");
}
So, after some testing and googling, I think it's your regex pattern.
Another answer here worked: Validate hexadecimal string using regular expression
I tested the match and it worked fine.
"^(0x|0X)?[a-fA-F0-9]+$"
if you don't want the 0x, go with: "^[a-fA-F0-9]+$"
I find that using an online tester like http://regexstorm.net/tester helps.
try this solution:
if (Regex.IsMatch(s, #"\A\b[0-9a-fA-F]+\b\Z"))
{
int temp = int.Parse(hexadecimalnum, System.Globalization.NumberStyles.HexNumber);
DecimalTxt.Text= temp.ToString();
BinaryTxt.Text = Convert.ToString(temp, 2);
}
else
{
MessageBox.Show("Invalid - please enter a hexadecimal value in this box");
}
or you can use TryPrase() Int64_TryParse to check if string is valid
long temp ;
if(long.TryParse(hexadecimalnum, System.Globalization.NumberStyles.HexNumber, null, out temp))
{
DecimalTxt.Text= temp.ToString();
BinaryTxt.Text = Convert.ToString(temp, 2);
}

CultureInfo.GetCultureInfo Causing incorrect format error

Everytime when I type in z as a input it fails. I don't understand what the problem is. It get the error " System.FormatException : Input string was not in a correct format" Dsales is a interger going into the converter to get converted into dollar and cents. Whats not correct about that?
using System;
using static System.Console;
using System.Globalization;
class HomeSales
{
static void Main()
{
string response;
int dsales = 0;
int esales = 0;
int fsales = 0;
int initial;
string damount;
string eamount;
string famount;
int damounti;
int eamounti;
int famounti;
WriteLine ("Enter a salesperson initial");
response = ReadLine();
//initial = Convert.ToInt32(response);
while (response == "d" || response == "D")
{
WriteLine ("Enter Line of sale");
damount = ReadLine();
damounti = Convert.ToInt32(damount);
dsales = dsales + damounti;
}
while (response == "z" || response == "Z")
{
WriteLine("Danielle sold {0}", dsales.ToString("C", CultureInfo.GetCultureInfo("en-US")));
}
}
}
You have incorrectly programmed your console loop.
Judging from your variable declarations and strings, your code intends to record sales amounts for different salespeople, reporting the total sale amount when sale entries are done.
The FormatException comes when you type "z" after the "Enter Line of Sale" prompt.
Instead of assuming that the user will always type a valid number, add a condition to check for a valid input before attempting to parse a number. The conditional check should also include the means to exit the loop early, or to at least avoid the code that parses a numerical value.
Also, as you're dealing with values interpreted as currency, consider using the System.Decimal (decimal) structure to store values, as calculations would be more accurate.

Using PromptforLetter and DisplayLetter in C#

Below is a homeowrk assignment I've been working on.
I need to create a class called FormattedOutput in a file called FormattedOutput.cs. That class will have the following methods:
char PromptforLetter(void) - this method will return a value
void DisplayLetter(char letter) - this method will accept a value to display
Main should be in a file named mainModule.cs
Main will PromptforLetter for each character in your name and store each character into a char data type.
Then DisplayLetter(letter1) should display each letter as:
the actual letter
the decimal value of the key
the hexadecimal value of the key
the octal value of the key
the binary value of the key
Information should be displayed first...
Then prompts for each letter of your name.
Then a Table showing each value
Char Decimal Hex Octal Binary
Here is the horrible mess I have at this time
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication1
{
public class formattedOutput
{
char PromptforLetter(string prompt)
{
string value;
char achar;
Console.WriteLine("A", prompt);
Console.WriteLine("L", prompt);
Console.WriteLine("M", prompt);
Console.WriteLine("A", prompt);
Console.Read();
value = Console.ReadLine();
achar=Convert.ToChar(value.Substring(0,1));
return achar;
}
void DisplayLetter (char letter)
{
Console.WriteLine("A");
Console.Read();
I'm fairly uncertain of what you're going for, and it might help to clear up your introduction to the problem (or instance, we don't need to know filenames and such, just give the relevant details). It also seems like you're asking quite a few questions, so I'm going to focus on what I think you actually mean to ask.
The impression I'm getting is that you are to write a console application in C#, with a method to read a single character from user-input, then another one to echo it back to them using several number formats.
If that is, in fact, the case, you probably want something like this:
public char PromptforLetter(string prompt)
{
Console.Write(prompt + " "); // This prints out the prompt with a space, and no
// following line break
// Now you have a choice. Should you take the first key that is pressed, or
// should the user have to press enter?
// Option 1:
char ret = Console.ReadKey().KeyChar;
Console.WriteLine(); // Not necessary, but it improves user experience
return ret;
// Option 2:
return Console.ReadLine()[0]; // take the first indexed character from the
// string entered by the user. Strings have
// integer-indexers, so you can access single them
// characters in kind of like you would if they were
// a string array.
}
Printing the character is a bit simpler:
public void DisplayLetter(char val)
{
Console.Write("Char: {0}", val);
Console.Write("Decimal: {0}", (int)val);
Console.Write("Hex: {0:X}", (int)val);
Console.Write("Octal: {0}", Convert.ToString((int)val, 8));
Console.Write("Binary: {0}", Convert.ToString((int)val, 2));
}
Beyond that, it's mostly just up to you and what the instructor is looking for, specifically.

How to check if first character of a string is a letter c# [duplicate]

This question already has answers here:
How to check first character of a string if a letter, any letter in C#
(4 answers)
Closed 8 years ago.
i need some help. I have to write a programm where you can do some calculation with matrices.
The User input should be for example: A=[1,2,3;4,5,6;7,8,9]
The user should be able to save up to 10 matrices. The user should be able to write operations like A+B or C*D
I want to check, if the first character of the users input is a letter, if not, i want to give an exception. Is there a method in c# where you can check if the first character is a letter. I want to save the letters into a string array so I can reference the name of the matrices to the int [,] which contains the matrices. Here is a snippet of my code:
int i = 0;
int[][,] ArrayContainer = new int[10][,];
int rowcount;
int columncount;
while (i < 10)
{
string input = Console.ReadLine();
string trimedinput;
if (input.Contains(" "))
{
trimedinput = input.Replace(" ", string.Empty);
}
else if (input == String.Empty)
{
break;
}
else if(!input.Contains("="))
{
Console.WriteLine("The definition of your matrix is not correct. Please type in 'help' if you need help.");
continue;
}
else
{
trimedinput = input;
}
}
Thank you for help!
you can use Char.IsLetter as shown below :-
for example :-
string str = " I am a string";
bool isLetter = !String.IsNullOrEmpty(str) && Char.IsLetter(str[0]);
For more information :-
http://msdn.microsoft.com/en-us/library/system.char.isletter.aspx
Use Char.IsLetter.
bool isLetter = Char.IsLetter(str[0]);
You could use char.IsLetter():
string foo = "Hello world";
bool isLetter = char.IsLetter(foo, 0);
You could use the the method IsLetter of Char type.
For instance if you have a string called test and you want to check if it's first character is a letter, you could check it out like below:
bool isLetter = Char.IsLetter(test[0])
For further documenation, please have a look here.

Char tryParse not working as I thought?

I have some problem with a method that I have done in c#. I'm trying to stop user from entering anything else then y and n. It's almost working that I want, but user can still enter more than one sign, and then it doesn't work! How can I do to also check if char is more than one char? I thought the tryParse solved that? Thanks!
// Method to check if item is food or not
private void ReadIfFoodItem()
{
Console.Write("Enter if food item or not (y/n): ");
if (char.TryParse(Console.ReadLine(), out responseFoodItem))
{
if(Char.IsNumber(responseFoodItem))
{
Console.WriteLine(errorMessage);
ReadIfFoodItem();
}
else
{
// Set true or false to variable depending on the response
if ((responseFoodItem == 'y' || responseFoodItem == 'Y'))
{
foodItem = true;
selectedVATRate = 12; // Extra variable to store type of VAT
}
else if ((responseFoodItem == 'n' || responseFoodItem == 'N'))
{
foodItem = false;
selectedVATRate = 25; // Extra variable to store type of VAT
}
else
{
Console.WriteLine(errorMessage);
ReadIfFoodItem();
}
}
}
}
The following code "works" in that it produces the expected results.
char responseFoodItem;
Console.Write("Enter if food item or not (y/n): ");
if (char.TryParse(Console.ReadLine(), out responseFoodItem))
{
// Set true or false to variable depending on the response
if ((responseFoodItem == 'y' || responseFoodItem == 'Y'))
{
Console.WriteLine("foodItem = true");
}
else if ((responseFoodItem == 'n' || responseFoodItem == 'N'))
{
Console.WriteLine("foodItem = false");
}
else
{
Console.WriteLine("Unrecognised input");
}
}
else
{
Console.WriteLine("Invalid input");
}
However, has others have pointed out using ReadKey is a better solution if you want to limit the input to a single key. It also means that the user doesn't have to press the Return/Enter key for the input to be accepted.
char represents a single character, so How can I do to also check if char is more than one char? I thought the tryParse solved that? seems a bit nonsensical... TryParse will try and parse a single character from your input and will explicitly fail if the value is null or has a length > 1.
Instead of checking a character, just check the string, e.g.:
string line = Console.ReadLine();
switch (line.ToUpperInvariant())
{
case "Y":
// Do work for y/Y
break;
case "N":
// Do work for n/N
break;
default:
// Show error.
break;
}
char.TryParse simply tries to parse the string supplied as an argument, it does not limit the number of characters that you can input to the console using Console.ReadLine.
When the user inputs more than a single character, char.TryParse will fail because the string returned by Console.ReadLine doesn't contain a single character.
You should use Console.Read instead.
How can I do to also check if char is more than one char?
string line = Console.ReadLIne();
If(!string.IsNullOrEmpty(line) && line.Length > 1)
for reading a single char use Console.ReadChar() instead.
Console.ReadLine allows users to type a string of any length and press enter.
How can I do to also check if char is more than one char? I thought the tryParse solved that?
From the manual page:
Converts the value of the specified string to its equivalent Unicode character. A return code indicates whether the conversion succeeded or failed....The conversion fails if the s parameter is null or the length of s is not 1.
Have you tried using Console.ReadKey instead of ReadLine?
To check it the user has inserted more then one char you could check the string length instead of use Char.TryParse
......
private void ReadIfFoodItem()
{
string answer=string.empty;
Console.Write("Enter if food item or not (y/n): ");
answer=Console.ReadLine()
if (answer.lenght>=1))
{
//error
.......
}
...............
This answer should help you: How can I limit the number of characters for a console input? C#
The console does not limit the user input (well it does, but to 256 characters), nor does char.TryParse which doesn't do anything at all to limit the input length.
You can try using Console.ReadKey
It's just one keystroke for the user and you know there won't be more than one char.
Why not comparing to the input'ed string?
And why not simplifying the comparison?
using System.Linq;
private static string[] ValidAnswers = new string[]{ "y", "yes" };
// Method to check if item is food or not
private void ReadIfFoodItem() {
Console.Write("Enter if food item or not (y/n): ");
string ans = Console.ReadLine();
// Checks if the answer matches any of the valid ones, ignoring case.
if (PositiveAnswers.Any(a => string.Compare(a, ans, true) == 0)) {
foodItem = true;
selectedVATRate = 12; // Extra variable to store type of VAT
} else {
foodItem = false;
selectedVATRate = 25; // Extra variable to store type of VAT
}
}
Alternatively, as others said, you can use Console.ReadKey().
Use Console.ReadKey() to limit the amount of characters. To test whether you have a Y or an N then you can compare the ASCII codes or use a regular expression.

Categories