I want to see how I can get the value entered in this console application to work inside a form textbox how can I do this?
Example entering 00000000 in console to be as if it were entered in the form so I guess I want them to be separate but work seamless any ideas. I cant figure out how to get the textbox to get the contents from the Console.Readline() of the console application.
This is and example of how I am trying to get it to work
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(" ", "");
}
}
[1]: http://i.stack.imgur.com/bAcDJ.jpg
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";
}
}
Create an instance of the form and pass in the variable you store when you do a readline into the textbox.
IsbnForm form = new IsbnForm();
You can pass the text in a few ways, via method:
//In the IsbnForm class
public SetTextboxText(String Text) { textbox.text = Text; }
//In the console application
form.SetTextboxText(isbn);
a variable such as:
//In the IsbnForm class
public String TextboxText { set { textbox.text = value; } }
//In the console application
form.TextboxText = isbn;
or just making the textbox control public, and then changing the value via
//In the console application.
form.textbox.text = isbn;
You'll need to keep the console program running when you show your form, either by having a readline, a loop that breaks when the form is closed or possibly using ShowDialog instead of Show.
See which one works properly and how you'd expect it to work.
form.Show();
Console.Readline();
or
while(FormRunning == false) { }
or
form.ShowDialog();
Related
I am not sure how to tackle this problem. I tried putting the do while loop in the method GetUserInput and then putting the for loop in the do while loop. It doesn't reset the question it just takes the number and adds it the numbers before it. Its a supposed to be a calculator program.
//This propgram will be used to make a calculator for the class project.
//The numbers are stored as floats as well as the result. Then displayed on console.
//V1 adds a do-while loop that repeats as long as the user wants.
//V2 adds a if and else logic for when the user input a character other than a number the program will close.
//V3 added a for-loop to increase the amount of numbers that can be considered in the calculation. It makes an array
//V4 added methods to get user input and sum the numbers
class MainClass
{
public static void Main(string[] args)
{
Console.WriteLine("Hello Ulises Sanchez");
//Define 3 floating point numbers to capture the 2 inputs and the result
//floats are used to capture a broader range of numbers
float[] userInput = new float[10];
//stores the number of inputs the user requests
int numberOfUserInputs;
//define strings to store data read and also user prompts
string inputString;
string doMorefunctions = "Add More Numbers Together - y = yes - anything else for no";
//variable to test the condition to continue with calculations
bool moreActions;
do
{
Console.Clear();
numberOfUserInputs = GetuserInput(userInput);
//adds the numbers together
Summation(userInput, numberOfUserInputs);
//reset moreAction
moreActions = false;
Console.WriteLine(doMorefunctions);
inputString = Console.ReadLine();
if (inputString == "y" || inputString == "Y")
moreActions = true;
} while (moreActions);
}
//Gets the number of user inputs and stores each in the userInput array
static int GetuserInput(float[] inputArray)
{
int numberOfInputs;
string userInputPrompt = "How many numbers do you want to enter?";
//string continueMessage = "Hit any key to continue";
string errorMessage = "Invalid Input";
string inputString;
bool TryAgain;
Array.Clear(inputArray, 0, 10);
//Gets number of inputs from user
Console.Write(userInputPrompt);
inputString = Console.ReadLine();
numberOfInputs = int.Parse(inputString);
//Get inputs
for (int i = 0; i < numberOfInputs; i++)
{
Console.Write("Enter variable number {0}: ", i + 1);
inputString = Console.ReadLine();
if (Single.TryParse(inputString, out float result))
{
//if input is valid convert to float
inputArray[i] = float.Parse(inputString);
}
else
{
TryAgain = false;
Console.WriteLine(errorMessage);
inputString = Console.ReadLine();
if (inputString == "y" || inputString == "Y") TryAgain = true;
//if input is not valid input exit program
//Console.WriteLine(continueMessage);
//Console.ReadLine();
//System.Environment.Exit(1);
}
}
return numberOfInputs;
}
//takes the user input and performs a summation calculation
static void Summation(float[] inputArray, int numberOfInputs)
{
float summationResult = 0.0f;
for (int i = 0; i < numberOfInputs; i++)
{
summationResult += inputArray[i];
}
//display result to the screen
Console.WriteLine("Summation = {0}", summationResult);
}
}
We have this concept of "don't repeat yourself" (DRY) so we look for ways to make code that repeats itself not do so. Every one of your methods repeats the print/ReadLine process for asking a question
Let's have a method that asks the user for a string:
public string Ask(string q){
Console.WriteLine(q);
return Console.ReadLine();
}
Now we can say:
string name = Ask("what is your name? ");
Suppose blank input is invalid, let's use a loop to repeat the question:
public string Ask(string q){
string a = "";
while(string.IsNullOrEmpty(a)){
Console.WriteLine(q);
a = Console.ReadLine();
}
return a;
}
If the user gives no answer, they are stuck in the loop and the question is repeated until they give a valid answer
Now let's reuse this to ask for an int:
public int AskInt(string q){
return int.Parse(Ask(q));
}
Here we reuse Ask within AskInt so we don't do the print/read thing again and we leverage the "cannot renter blank" validation we already write
This however explodes if the user enters non ints
So let's use int.TryParse and keep looping while they enter garbage that doesn't parse;
public int AskInt(string q){
bool success = false;
into a=0;
while(!success){
success = int.TryParse(Ask(q), out a);
}
return a;
}
The user can only get to the last line if they enter an int
If you also want to add range validation, for example, you can put an int min, int max into your method parameters and inside the loop do success = success && a <= && a >= min
int guess = AskInt("enter a number between 1 and 10: ", 1, 10);
The idea is to write one method that does one thing really well I.e. "ask the user for a string" and then reuse that when we write the next method that does one thing well, so we end up with two methods that do two things well. Giving the methods a sensible name allows us to package up that bit of logic they do into a few words and make out code read like a book. It doesn't need as many comments then
//ask the user what their next guess is
int guess = AskInt("enter a number between 1 and 10: ", 1, 10);
This comment isn't needed; we can easily deduce the same just by reading the code.
I am trying to create 7 BOOM game. if you don't know the rules, everyone takes turns and says the next number but if the number can be divided by seven or contain seven you should say BOOM instead. so in my version, you insert a number and the program should show you all the numbers to that point.
So here is my problem, I succeeded in implementing the first part but I am having a problem with the second one. This is what I have until now:
class Program
{
static void Main(string[] args)
{
int num1 = int.Parse(Console.ReadLine());
int num2 = 0;
bool boolean;
while (num1>num2)
{
num2++;
if (num2%7 == 0)
{
Console.Write("BOOM, ");
}
else
{
Console.Write(num2 + ", ");
}
}
}
}
Just change your validation to:
if (num2%7 == 0 || num2.ToString().IndexOf('7') != -1)
{
// (..)
}
The IndexOf function looks for and returns the position of a substring in a string. If it is not found, it returns -1.
As pointed by #Dimitry, another option is
if (num2%7 == 0 || num2.ToString().Contains('7'))
{
// (..)
}
This uses the extension method Contains that returns true or false if the substring exists on the string.
public static void Main()
{
Console.Write("Please enter a number: ");
int number = int.Parse(Console.ReadLine());
// validate number here....
for (int i = 1; i <= number; i++)
{
string value = IsMultipleOrContains7(i) ? "BOOM" : i.ToString();
Console.WriteLine(value);
}
Console.WriteLine("Press any key to continue...");
Console.ReadKey();
}
public static bool IsMultipleOrContains7(int number)
{
if (number % 7 == 0)
{
return true;
}
return number.ToString().Contains("7");
}
I'm trying to write line where if text (anything other than number) typed it shows error message that it is not number and ask user to type again.
Also I have implanted that number must be 20 or higher which works fine and when ever user input less than 20 it shows error message and ask user again..
so my problem is that it shows error message for everything including number less than 20 and text.
So how can I make else statement that shows different message if text is type rather than number?
static double InputFuel() {
double fFuel;
string text;
bool badValue = true;
Console.Write("Enter amount of fuel used in litres : ");
//Check if fule entered is greater than 20, if not ask again
do {
text = Console.ReadLine();
if (double.TryParse(text, out fFuel) && fFuel >= 20) {
badValue = false;
}
else {
Console.WriteLine("\n\t {0} is below the minimum value of 20 \n\n", text);
Console.Write("Please re-enter a number greater than 20 : ");
}
} while (badValue);
return fFuel;
}//end InputFuel
I tried something like this but not working
else (!int.TryParse(text, out num) {
Console.WriteLine("\n\t {0} is not a number \n\n", text);
}
Firstly I would check if input is number and after that if number is greater than 20
static double InputFuel() {
double fFuel;
string text;
bool badValue = true;
Console.Write("Enter amount of fuel used in litres : ");
//Check if fule entered is greater than 20, if not ask again
do {
text = Console.ReadLine();
if (!double.TryParse(text, out fFuel) {
Console.WriteLine("\n\t {0} is not a number \n\n", text);
}
else if (fFuel >= 20) {
badValue = false;
}
else {
Console.WriteLine("\n\t {0} is below the minimum value of 20 \n\n", text);
Console.Write("Please re-enter a number greater than 20 : ");
}
} while (badValue);
return fFuel;
}//end InputFuel
You can your modify your current condition to be nested like below
if (double.TryParse(text, out fFuel)) {
if(fFuel >= 20) badValue = false;
else {
Console.WriteLine("\n\t {0} is below the minimum value of 20 \n\n", text);
Console.Write("Please re-enter a number greater than 20 : ");
}
}
else {
Console.WriteLine("\n\t {0} is not a number \n\n", text);
}
If you're looking for 'more advanced' or 'more enterprise-like' way of validating user input you can create a struct or class that will do the validation and provide some information about it :
class InputValidator
{
public string Input { get; set; }
public bool IsValidInput { get; set; }
public bool IsAboveThreshHold { get; set; }
public bool IsNumber { get; set; }
public double Litres { get; set; }
public ValidationResult() { }
public ValidationResult(string text)
{
double litres; Input = text;
if (double.TryParse(text, out litres))
{
Litres = litres;
IsAboveThreshHold = litres > 20;
IsNumber = true;
}
IsValidInput = IsNumber && IsAboveThreshHold;
}
public void ShowErrorMessage()
{
if (!IsNumber)
{
Console.WriteLine($"\n\t {Input} is not a valid number \n\n");
Console.Write("Please re-enter a number greater than 20 : ");
return;
}
if(!IsAboveThreshHold)
{
Console.WriteLine($"\n\t {Input} is below the minimum value of 20 \n\n");
Console.Write("Please re-enter a number greater than 20 : ");
}
}
}
And use this class very easily :
static double InputFuel()
{
var result = new InputValidator();
Console.Write("Enter amount of fuel used in litres : ");
//Check if fule entered is greater than 20, if not ask again
while (!result.IsValidInput)
{
result = new InputValidator(Console.ReadLine());
if (!result.IsValidInput) result.ShowErrorMessage();
}
return result.Litres;
}
P.S.
While in simple cases this would be an overkill but in more complex cases that are common in enterprise projects this approach is much better to use.
I am trying to check if a textbox contains a number. The problem is that it always returns that it contains a non-numeric character.
I've tried several ways, but none of them seems to work.
One of the ways I've tried is:
if( Regex.IsMatch(tb.Text.Trim(), #"^[0-9]+$")) // tb.Text is the textbox
It does not matter what I enter in the textbox, it always returns that it contains a non-numeric character (I tried entering 1-9, 'a', 'b')
You could just parse the string to a specific number type, i.e.
double result;
if (!double.TryParse(tb.Text, out result))
{
//text is not a valid double;
throw new Exception("not a valid number");
}
//else the value is within the result variable
From your regex it seems that you need only integer values, so you should use int.TryParse or long.TryParse instead.
Quick and dirty test program:
void Main()
{
TestParse("1");
TestParse("a");
TestParse("1234");
TestParse("1a");
}
void TestParse(string text)
{
int result;
if (int.TryParse(text, out result))
{
Console.WriteLine(text + " is a number");
}
else
{
Console.WriteLine(text + " is not a number");
}
}
Results:
1 is a number
a is not a number
1234 is a number
1a is not a number
You could replace your Regex for this:
if(Regex.IsMatch(tb.Text.Trim(), #"[0-9]"))
Or for this:
if(Regex.IsMatch(tb.Text.Trim(), #"\d"))
you can use TryParse:
int value;
bool IsNumber = int.TryParse(tb.Text.Trim(), out value);
if(IsNumber)
{
//its number
}
private void btnMove_Click(object sender, EventArgs e)
{
string check = txtCheck.Text;
string status = "";
for (int i = 0; i < check.Length; i++)
{
if (IsNumber(check[i]))
status+="The char at "+i+" is a number\n";
}
MessageBox.Show(status);
}
private bool IsNumber(char c)
{
return Char.IsNumber(c);
}
The program works in its current for but I would like to make it more object oriented like its design using constructors and such but I don't know where to start and how to make it work. I would like your insight and examples on how you would accomplish this task? Here is a sample UML for what I am trying to do.
Original Design
public static class IsbnConsole
{
public static void Main(string[] args)
{
Console.Write("Enter a valid 10 digit ISBN Number ");
string isbn = checkIsbnClass.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 (checkIsbnClass.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 checkIsbnClass
{
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(" ", "");
}
Newly Designed Method Using Constructors
public class isbn
{ //attributes
private string isbnNum;
//method
public string GetIsbn()
{
return this.isbnNum;
}
//constructor
public isbn()
{
Console.Write("Enter Your ISBN Number: ");
this.isbnNum = Console.ReadLine();
}//end default constructor
//method
public string displayISBN()
{
return this.GetIsbn();
}
public static void Main(string[] args)
{
//create a new instance of the ISBN/book class
isbn myFavoriteBook = new isbn();
//contains the method for checking validity
bool isValid = CheckDigit.CheckIsbn(myFavoriteBook.GetIsbn());
//print out the results of the validity.
Console.WriteLine(string.Format("Your book {0} a valid ISBN",
isValid ? "has" : "doesn't have"));
Console.ReadLine();
}
public static class CheckDigit
{ // attributes
public static string NormalizeIsbn(string isbn)
{
return isbn.Replace("-", "").Replace(" ", "");
}
public static bool CheckIsbn(string isbn) // formula to check ISBN's validity
{
if (isbn == null)
return false;
isbn = NormalizeIsbn (isbn);
if (isbn.Length != 10)
return false;
int result;
for (int i = 0; i < 9; i++)
if (!int.TryParse(isbn[i].ToString(), out result))
return false;
int sum = 0;
for (int i = 0; i < 9; i++)
sum += (i + 1) * int.Parse(isbn[i].ToString());
int remainder = sum % 11;
if (remainder == 10)
return isbn[9] == 'X';
else
return isbn[9] == (char)('0' + remainder);
}
public static class IsbnConsole
{
public static void Main(string[] args)
{
Console.Write("Enter a valid 10 digit ISBN Number ");
string isbn = checkIsbnClass.DestabilizeIsbn(Console.ReadLine()); // Normalizes the input and puts it on string "str"
Isbn isbn = new Isbn(Console.In)
if (!isbn.CheckLength())
Console.WriteLine("The number you have entered is not a valid ISBN try again."); // Print invalid number
}
else if (isbn.HasCheckDigit)
{
if (isbn.CheckNumber(isbn))
Console.WriteLine("The number you have entered is a Valid ISBN");
else
Console.WriteLine("The number you have entered is not a valid ISBN try again."); // Print invalid number
}
else
{
Console.WriteLine("The Check digit that corresponds to this ISBN number is " + isbn.GetCheckDigit(isbn) + "."); // Print the checksum digit
}
Console.ReadLine();
}
public class Isbn
{
public Isbn(TextReader cin)
{
/// do stuff here.
}
public bool CheckLength()
{
/// do stuff here.
}
public bool HasCheckDigit { get { ..... } }
public int GetCheckDigit() {..... }
public bool CheckNumber() {......}
}
I do think the original design makes sense. I mean the ISBN has no other purpose than to be checked. I don't see any benefit in trying to materialize it as an instance class.
But just for academic purposes, you may ask yourself several questions here:
- Do you want to materialize the ISBN itself ? Create an ISBN class containing properties for its value and methods for the checks (this is James Curran's solution)
- Do you want to materialize the fact that you check an ISBN ? Create an ISBNChecker class that will contain methods to perform the checks
- Both ? an ISBN instance will be created from the Console input and pass as a parameter to the ISBNChecker instance.
By materialize, I mean "create an instance class"