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.
Related
I am fairly new to programming so have some mercy ;)
I am trying to build a program that can solve equations and give gradient and so on in c#, so I can make it more complex gradually. Problem is, there appears to be a wrong value from my input when I tried to start building it.
Console: Given value for "a":
9 The Output: 57
My Code:
using System;
namespace ConsoleApp1
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Input an linear Eqasion in the following Pattern -- a * x + b");
Console.Write("Given value for \"a\":");
decimal aValue;
aValue = Console.Read();
Console.Write(aValue);
}
}
}
Console.Read() returns an int, but not in the way you think. It returns the numeric value of the typed character, not the human-intuitive interpretation of a character that coincidentally happens to be a number. Consider for example what it would return if you type a letter, or any other non-numeric character.
And what is the numeric (decimal) value for the character '9'? 57 is.
It sounds like you want to read the line, not the character. For example:
string aValue;
aValue = Console.ReadLine();
Console.Write(aValue);
Remember that you'll need to press return to send the line to the application.
If you'll later need the value to be numeric, you'll still want to input the string but will want to parse it. For example:
string aValue;
aValue = Console.ReadLine();
if (decimal.TryParse(aValue, out decimal numericValue)
{
Console.Write(numericValue);
}
else
{
// The value could not be parsed as a decimal, handle this case as needed
}
Console.Read returns the character code entered on the command line in this scenario. The ASCII character code of 9 is 57. If you're wanting numeric input, you'd be better using Console.ReadLine with Decimal.Parse (or better yet, Decimal.TryParse)
It is also worth noting that Console.Read only returns one character at a time, meaning for any inputs past 1 digit you'll need special handling. I highly recommend using ReadLine and parsing the string over handling converting the character codes to the number they represent.
This question is more of a "Why can't I do this/What am I doing wrong" as I have managed to accomplish what the program should do, but it raised more questions around why certain things work the way they do.
For starters, the goal of this project is to capture a single character from the Console window (using Console.Read()/.ReadLine()), convert it to a string with the Convert class, and then write it to the Console window.
I've managed to get my project to have this functionality with the following code:
namespace ReadConvertWrite
{
class Program
{
static void Main(string[] args)
{
String input = Console.ReadLine();
try
{
Convert.ToInt32(input);
}
catch (Exception)
{
}
Console.WriteLine(input);
Console.ReadLine();
}
}
}
Given that this seems like a pointless exercise since the conversion is unnecessary I wanted to make it necessary by using the .Read() method instead of .ReadLine(). Which leads me to my question:
Why is it that .Read() always prints the hexadecimal value of the character inputted into the console despite the MSDN documentation making it sound like .Read() and .ReadLine() work the same way apart from reading a single character Vs a line, and beyond that why do none of the Convert class methods I've tried (.ToInt, .ToString, etc) work to actually give me output other than the hexadecimal values?
Here's what I've tried so far:
namespace ReadConvertWrite
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine(Convert.ToString(Console.Read()));
Console.ReadLine();
Console.ReadLine();
}
}
}
And:
namespace ReadConvertWrite
{
class Program
{
static void Main(string[] args)
{
var input = 0;
input = Console.Read();
String InputString = Convert.ToString(input);
Console.ReadLine();
Console.ReadLine();
}
}
}
Console.Read returns an integer representing a character. Console.ReadLine returns a string.
When you do Console.WriteLine(Console.ReadLine()), you're simply echoing your input. When you do Console.WriteLine(Convert.ToString(Console.Read())), you're taking the numeric value of the character and printing it as a number.
Convert.ToString(int) will not interpret the integer as a character - that would be rather ridiculous. Would you expect Convert.ToString(42) to print *? You need to cast the integer to a character instead:
Console.WriteLine((char)Console.Read());
Most likely, you don't want to use Console.Read anyway - it's a rather specific thing dealing with old-school CLI, rather than anything very useful for a typical console program, unless you need to stream lots of characters and want to avoid allocating huge strings unnecessarily.
Make sure to handle end-of-file correctly - Console.Read() will return -1 when the input stream ends, which is not a valid value for char.
If you hover your mouse over Read() it will show you it returns an int, not a string. Converting an 'int' to a string will just be a string representation of an int. To get a character from an int, cast it back to a char.
The cast to a char will convert the number back into its character representation.
Console.WriteLine((char)Console.Read());
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
}
}
}
I want to be able to use the contains function the same way the like operator works in sql. So when I call .contains(%This%%%%%%is%%my%string%%) from a list or whatever such as "This is my string " then the function will return true. I've done a lot of searching and it seems like a lot of people would like this function. So how can this be done or how can a custom like function with the same functionality be made?
EDIT
Thank you, for the quick response. I was able to use a regular expressions inside of my own custom Like function. Below is the code for anyone else who wants to use something similar to SQL Like. In this code the user would input the databaze value and then spaces in that value are replaced with .* to ignore anything in-between the values.Just like using the % to replace spaces and values in SQL. I can then use .Like on my string value called testValue that I am searching through to return true or false depending on if the words or whatever are in my string. I also added ToUpper to ignore the case.
//C# Like function
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
namespace sqllinqstuff
{
class Program
{
static void Main(string[] args)
{
string testValue = "Big RED Car";
string databaze = "big red CAR";
string databaze3 = databaze.Replace(" ", ".*");
databaze3 = databaze3.Replace(" ", ".*");
Console.WriteLine(databaze3);
Console.WriteLine(testValue.Like(databaze3));
Console.Read();
}
}
public static class CaseyStringExtension
{
public static bool Like(this string str,string value)
{
if (!string.IsNullOrEmpty(str))
{
Regex r = new Regex(value.ToUpper());
if (r.IsMatch(str.ToUpper()))
return true;
}
return false;
}
}
}
The result of this test will be true.
The way this would be done is with Regex. The syntax is not the same as a SQL LIKE query so there will be a bit of a learning curve. This is a good tutorial site I often reference, it can get you started with the basics.
Translating your original string you asked about, the regex search pattern would be
.*This.*is.*my.*string.*
Once you get good at it you can do searches like this one I helped create for a password complexity checker
(?=^.{8,}$)(?=.*[a-z])(?=.*[A-Z])(?=.*[\W_])(?=^.*[^\s].*$).*$
The above search looks for a string that has at least 8 characters with at least one lower case letter, one upper case letter, one special character, and no white-space characters.
I cannot read a second character with Console.Read() method. I mean I don't get any Prompt to read the second character from Keyboard. Any help please? Also, I understand that character is by default an int but we still need to convert it to char when reading from input, is it right? The code below reads the first char but terminates with the second.
public static void Main()
{
Console.WriteLine("The First Character?:");
char firstChar=Convert.ToChar(Console.Read());
Console.WriteLine("The Second Character?:");
char secondChar=Convert.ToChar(Console.Read());
}
Looks like Console.ReadKey() is what you actually want.
Please see Console.Read. Specifically, this part:
The Read method blocks its return while you type input characters; it terminates when you press the Enter key. Pressing Enter appends a platform-dependent line termination sequence to your input (for example, Windows appends a carriage return-linefeed sequence). Subsequent calls to the Read method retrieve your input one character at a time. After the final character is retrieved, Read blocks its return again and the cycle repeats.
Perhaps this code is closer to what you're looking for...
public static void Main()
{
Console.WriteLine("The First Character?:");
char firstChar = Convert.ToChar(Console.ReadKey().KeyChar);
Console.WriteLine();
Console.WriteLine("The Second Character?:");
char secondChar = Convert.ToChar(Console.ReadKey().KeyChar);
}
Your second Console.Read() is consuming the carriage return terminating the first read.
Console.ReadKey is a bit friendlier to use, since it doesn't require a terminating carriage return. If you want to continue using Console.Read, you might try consuming and discarding the carriage return before the second prompt, like:
public static void Main()
{
Console.WriteLine("The First Character?:");
char firstChar = Convert.ToChar(Console.Read());
Console.Read(); // consume carriage return
Console.WriteLine("The Second Character?:");
char secondChar = Convert.ToChar(Console.Read());
Console.WriteLine(secondChar);
}