How do I locate a specific digit - c#

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");
}

Related

How do I detect an infinite loop occuring in my code?

So my code is to check if a given number is a 'happy number'. It squares each digit of the number, adds them and continues to do so until either the result of the addition is 1 (which means it is a happy number) or until it results in a 4 (which means it is not a happy number).
What's happening is that there are many numbers which cause an infinite loop (therefore meaning they are not a happy number) and I'm wondering how I would construct my code so that it will detect when there's an infinite loop occuring? I have some ideas but all flawed.
My code is as follows:
using System;
namespace Happy_numbers_problem
{
class Program
{
static int HappyNumbers(string Number)
{
string Output = Number;
while ((Convert.ToInt32(Output) != 1) && (Convert.ToInt32(Output) != 4))
{
string Result2 = "0";
for (int Index = 0; Index < Output.Length; Index++)
{
string Character = Output.Substring(Index, 1);
int Calc = Convert.ToInt32(Character);
int Result = Calc * Calc;
//Adding Result2 and Result, then turning it into a string.
Result2 = Convert.ToString(Convert.ToInt32(Result2) + Result);
if (Index == (Output.Length) - 1)
{
Output = Result2;
}
}
}
return Convert.ToInt32(Output);
}
static void Main(string[] args)
{
Console.WriteLine("Please enter a number");
string Number = Console.ReadLine();
int Output = HappyNumbers(Number);
if (Output == 1)
{
Console.WriteLine(Number + " is a happy number");
}
else if (Output == 4)
{
Console.WriteLine(Number + " is not a happy number");
}
else
{
Console.WriteLine(Number + " is not a happy number");
}
}
}
}
The problem resides in your while condition. If your output needs to be 1 or 4 to break out of the loop and deliver the output to latter be analysed, you have to use the operator or || instead of the operator and &&.

I need to check 3 things in a 1 do while loop and I am out of ideas

I am basically building a lottery game, and I need to check several parameters in 1 loop.
I need to check that the user has actually input a number and not something else, I need to check if that number is within the range of 1 to 47, and I need to check that the user did not input the same number.
If any of those conditions are not met the user is prompted to repeat himself until all of the conditions are met.
But I am stuck, and I am not really sure how to proceed with the checking of the same number.
for (int i = 0 ; i < 6; i++)
{
do
{
string input = Console.ReadLine();
isValidNumber = int.TryParse(input, out valueFromUser);
isNumberInRange = valueFromUser > 0 && valueFromUser < 47;
Console.WriteLine("Please enter a number");
if (!isNumberInRange)
{
Console.WriteLine("Please input only numbers bigger than 0 and less than 47");
}
else if (!isThesame)
{
}
} while(!isValidNumber || !isNumberInRange || !isThesame);
lucky[i] = valueFromUser;
}
Console.WriteLine("Your chosen numbers are: {0} ,{1}, {2}, {3}, {4}, {5} ", lucky[0], lucky[1], lucky[2], lucky[3], lucky[4], lucky[5]);
You can use the Array.IndexOf method to search for an item in an array. If that item is not found, it will return -1. So if this method returns anything other than -1, we know that the user has entered the number before.
if (i == 0) {
isThesame = false;
} else if (Array.IndexOf(lucky, valueFromUser, 0, i - 1) != -1) {
isThesame = true;
}
Or simply:
isThesame = i != 0 && Array.IndexOf(lucky, valueFromUser, 0, i - 1) != -1;
Note that we only search the array up to the element before lucky[i], this is because technically, the rest of the array hasn't been "filled". We don't want to take the initial values at those indices into account.
This also means that we need to handle the special case of i == 0. When i == 0, i - 1 will be negative, and passing that to Array.IndexOf will throw an exception, which is why we handle it separately.
Probably not the most elegant solution. Obviously, the code could be trimmed, just a tad:
using System;
using System.Collections.Generic;
using System.Diagnostics;
namespace ConsoleApp1
{
class Program
{
static void Main(string[] args)
{
int valueFromUser;
//Method 1
List<int> lucky = new List<int>();
for (int i = 0; i < 5; i++)
{
do
{
Console.WriteLine("Please enter a number");
if (int.TryParse(Console.ReadLine(), out valueFromUser))
{
if (!lucky.Contains(valueFromUser) && (valueFromUser > 0 && valueFromUser < 48))
{
lucky.Add(valueFromUser); break;
}
}
} while (true);
}
Console.WriteLine($"Your chosen numbers are: {lucky[0]}, {lucky[1]}, {lucky[2]}, {lucky[3]}, {lucky[4]}"); Console.ReadKey();
//Method 2
int[] lucky2 = new int[5];
for (int i = 0; i < 5; i++)
{
do
{
Console.WriteLine("Please enter a number");
if (int.TryParse(Console.ReadLine(), out valueFromUser))
{
if ((Array.IndexOf(lucky2, valueFromUser) == -1) && (valueFromUser > 0 && valueFromUser < 48))
{
lucky2[i] = valueFromUser; break;
}
}
} while (true);
}
Console.WriteLine("Your chosen numbers are: {0}, {1}, {2}, {3}, {4} ", lucky2[0], lucky2[1], lucky2[2], lucky2[3], lucky2[4]); Console.ReadKey();
}
}
}

How can I make a program loop back to the start if else is true? C#

Couldn't find any other answer on the site that covers this. If else is run and an error message is displayed, is it possible to restart the program by looping back to the start instead of restarting the console?
class Program
{
static void Main(string[] args)
{
int User;
int Array;
StreamWriter outfile = new StreamWriter("C://log.txt");
Console.WriteLine("Input an number between 1 and 100");
User = Convert.ToInt32(Console.ReadLine());
if (User < 101 && User > 0)
{
for (Array = 1; Array <= User; Array++)
{
Console.WriteLine(Array + ", " + Array * 10 * Array);
outfile.WriteLine(Array + ", " + Array * 10 * Array);
}
{
Console.WriteLine("Press Enter To Exit The Console");
outfile.Close();
Console.ReadLine();
}
}
else
{
Console.WriteLine("Sorry you input an invalid number. ");
Console.ReadLine();
}
}
}
Sorry! To be more clear I need to make the Program start again if the user inputs an invalid number
Thanks for the help!
You can do this instead
User = Convert.ToInt32(Console.ReadLine());
while (User >= 101 || User <= 0)
{
Console.WriteLine("Sorry you input an invalid number. ");
User = Convert.ToInt32(Console.ReadLine());
}
An easy way of doing this is placing your code inside a while loop, so that the code keeps repeating. The only way to exit the loop would be for the condition you just set in the if clause to be true. So something along the lines of:
class Program
{
static void Main(string[] args)
{
int User;
int Array;
bool isUserWrong = true; //This is a flag that we will use to control the flow of the loop
StreamWriter outfile = new StreamWriter("C://log.txt");
while(isUserWrong)
{
Console.WriteLine("Input an number between 1 and 100");
User = Convert.ToInt32(Console.ReadLine());
if (User < 101 && User > 0)
{
for (Array = 1; Array <= User; Array++)
{
Console.WriteLine(Array + ", " + Array * 10 * Array);
outfile.WriteLine(Array + ", " + Array * 10 * Array);
}
isUserWrong = false; // We signal that we may now leave the loop
}
else
{
Console.WriteLine("Sorry you input an invalid number. ");
Console.ReadLine();
//Note that here we keep the value of the flag 'true' so the loop continues
}
}
Console.WriteLine("Press Enter To Exit The Console");
outfile.Close();
Console.ReadLine();
}
}

Converting a program with just static methods to one that uses objects instead

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"

Get input from console into a form

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();

Categories

Resources