The closest thing I found to answering this question was converting several string inputs into an array using a for loop.
I just want to take 1 string and convert the first 7 digits into an int array.
This code takes integer values of characters and then tests them against the Unicode values to return true if it is valid or false to reiterate the while loop and ask for input again. When I do this with the Console.Read(); method, and put in an invalid value first, it will say that my code is invalid for 7 more iterations. That means console.Read() has to run 7 more times even if the string has valid input.
public static void GetDigits(ref int[] callNumberArray, ref bool valid)
{
Console.WriteLine("Please enter the code you wish to dial.");
while ( valid == false)
{//This loop will reiterate the read() function if the code is not valid.
valid = true;
for (int i = 0; i < 7; i++ )
{
if (i != 6 && i!= 5 && i != 5 && i != 4 && i != 3 && i != 2 && i != 1 && i != 0)
{
i = 0;
}
callNumberArray[i] = Console.Read();// I want to change this
}
for (int i = 0; i < 7; i++)
{
if (i != 6 && i != 5 && i != 5 && i != 4 && i != 3 && i != 2 && i != 1 && i != 0)
{
i = 0;
}
if (callNumberArray[0] == 53)
{
valid = false;
}
if (callNumberArray[i] < 49)
{
valid = false;
}
if (callNumberArray[i] > 57 && callNumberArray[i] < 65)
{
valid = false;
}
if (callNumberArray[i] > 90 && callNumberArray[i] < 97)
{
valid = false;
}
if (callNumberArray[i] > 122)
{
valid = false;
}
}
if (valid == false)
{
Console.WriteLine("You entered an invalid code. Please re-enter your code.");
}
}
I think you should use Regex, example:
MatchCollection matchList = Regex.Matches(Content, Pattern);
var list = matchList.Cast<Match>().Select(match => match.Value).ToList();
I just want to take 1 string and convert the first 7 digits into an int array.
string subString = Console.ReadLine().Substring(0,7);
//Check if the whole string is a parsable number
if(int.TryParse(subString) == false)
{
Console.WriteLine("Not a valid number...");
return;
}
//convert it an int[]
int[] values = subString.ToCharArray().Select( value => int.Parse(value.ToString())).ToArray();
That's it basically, if you want to do it character by character that's fine, too, but's it's far easier to check for a number using int.TryParse() or a regex [0-9] (per character) if you're confortable with that.
Not sure about the "algorithm" you wrote and I agree with Sergey Berezovskiy that the if's looks weird, anyway this should answer your specific question:
public static void GetDigits(ref int[] callNumberArray, ref bool valid)
{
Console.WriteLine("Please enter the code you wish to dial.");
while ( valid == false)
{//This loop will reiterate the read() function if the code is not valid.
valid = true;
for (int i = 0; i < 7; i++ )
{
if (i != 6 && i!= 5 && i != 5 && i != 4 && i != 3 && i != 2 && i != 1 && i != 0)
{
i = 0;
}
callNumberArray[i] = Console.Read();// I want to change this
}
for (int i = 0; i < 7; i++)
{
if(!valid) break;
if (i != 6 && i != 5 && i != 5 && i != 4 && i != 3 && i != 2 && i != 1 && i != 0)
{
i = 0;
}
if (callNumberArray[0] == 53)
{
valid = false;
}
if (callNumberArray[i] < 49)
{
valid = false;
}
if (callNumberArray[i] > 57 && callNumberArray[i] < 65)
{
valid = false;
}
if (callNumberArray[i] > 90 && callNumberArray[i] < 97)
{
valid = false;
}
if (callNumberArray[i] > 122)
{
valid = false;
}
}
if (valid == false)
{
Console.WriteLine("You entered an invalid code. Please re-enter your code.");
}
}
Here is method which prompts user to input phone number, denies invalid characters and shows current phone number with placeholder for numbers left to input:
private static int[] GetPhoneNumber(int phoneLength = 7)
{
List<int> phoneNumbers = new List<int>();
while (true)
{
EditorFor("Phone", String.Concat(phoneNumbers), phoneLength);
var key = Console.ReadKey(intercept: true);
if (key.Key == ConsoleKey.Escape)
return new int[0]; // return empty array if user cancelled input
var c = key.KeyChar;
if (!Char.IsDigit(c))
continue;
phoneNumbers.Add(Int32.Parse(c.ToString()));
if (phoneNumbers.Count == phoneLength)
{
EditorFor("Phone", String.Concat(phoneNumbers), phoneLength);
return phoneNumbers.ToArray();
}
}
}
Prompt for input:
private static void EditorFor(string label, string value, int length)
{
Console.SetCursorPosition(0, Console.CursorTop);
Console.Write(new String(' ', Console.WindowWidth));
Console.SetCursorPosition(0, Console.CursorTop);
int charactersLeftToInput = length - value.Length;
string placeholder = new String('*', charactersLeftToInput);
Console.Write("{0}: {1}{2}", label, value, placeholder);
Console.CursorLeft -= charactersLeftToInput;
}
Usage:
Console.WriteLine("Please enter the code you wish to dial.");
int[] code = GetPhoneNumber(); // if you want default length
Console:
Okay so After much deliberation I decided to use a separate Console.Read(); for each element in the array and now it's doing what I want it to do.
while ( valid == false)
{
valid = true;
callNumberArray[0] = Console.Read();
callNumberArray[1] = Console.Read();
callNumberArray[2] = Console.Read();
callNumberArray[3] = Console.Read();
callNumberArray[4] = Console.Read();
callNumberArray[5] = Console.Read();
callNumberArray[6] = Console.Read();
//etc etc...
Related
I am very new to C# and while loops. Does anyone know how to stop it? It keeps printing the first if-statement. Here is the code:
const int Year = 400;
const int LeapYear = 4;
const int NoLeapYear = 100;
int input = 0;
input = int.Parse(Console.ReadLine());
while (input != 0)
{
Console.WriteLine("Enter a number: ");
if (input > 0 && input % LeapYear == 0 || input % Year == 0)
{
Console.WriteLine($"{input} is a leap year.");
}
if (input > 0 && input % NoLeapYear != 0)
{
Console.WriteLine($"{input} is not a leap year.");
}
if (input < 0)
{
Console.WriteLine("Year must be positive!");
}
if (input == 0)
{
Console.WriteLine("End of program");
}
}
You have to read the input inside the while loop:
const int Year = 400;
const int LeapYear = 4;
const int NoLeapYear = 100;
int input = -1; // initialize to something different than zero, to enter the while loop (or use do while loop instead of while loop)
while (input != 0)
{
Console.WriteLine("Enter a number: ");
input = int.Parse(Console.ReadLine()); // you were missing this line
if (input > 0 && input % LeapYear == 0 || input % Year == 0)
{
Console.WriteLine($"{input} is a leap year.");
}
if (input > 0 && input % NoLeapYear != 0)
{
Console.WriteLine($"{input} is not a leap year.");
}
if (input < 0)
{
Console.WriteLine("Year must be positive!");
}
if (input == 0)
{
Console.WriteLine("End of program");
}
}
Consider using a do while loop in this case.
If you are using loop just and break to true statement It will breaks it
while (input != 0) {
conditions;
break; // Breaks the loop
}
Use the break; keyword to stop any loop in C# not just C# in many languages also break is used to stop loops
Or,
Satisfy the condition to opposite of what you have it will break/stop the loop
use break (https://www.w3schools.com/cs/cs_break.php)
int i = 0;
while (i < 10)
{
Console.WriteLine(i);
i++;
if (i == 4)
{
break;
}
}
How do i use operands in this code? What can i do to resolve this problem? Any suggestions or links to tutorials would be appreciated.
Operator '%' cannot be applied to operands of type 'string' 'int'
int i = 0;
double[] arr1 = new double[20];
for (i = 0; i < 20; i++)
{
Console.Write("Enter a number (0=stop): ");
var year = Console.ReadLine();
if (year == "0") break;
arr1[i] = int.Parse(year);
while (year != 0)
{
if (((year % 4 == 0) && (year % 100 != 0)) || (year % 400 == 0))
{
Console.WriteLine($"{year} is a leap year.");
}
else if (year < 0)
{
Console.WriteLine($"Year must be positive!");
}
else
{
Console.WriteLine($"{year} is not a leap year.");
}`
You are close. You are already parsing the string to an int. Just use that instead of the string year when doing your calculations. Also, I'm not sure what you're trying to do with that while loop but I don't think you need it. It seems to just cause your program to go in an infinite loop because while is evaluating year but there is no opportunity to change the year value within the while loop.
void Main()
{
int i = 0;
double[] arr1 = new double[20];
for (i = 0; i < 20; i++)
{
Console.Write("Enter a number (0=stop): ");
var line = Console.ReadLine();
int numYear = int.Parse(line);
arr1[i] = numYear;
string message = "" ;
if (line != "0")
{
if (numYear < 0)
{
message = "Year must be positive!";
}
else if ((numYear % 4 == 0) && (numYear % 100 != 0)) || (numYear % 400 == 0))
{
message = $"{numYear} is a leap year.");
}
else
{
message = $"{numYear} is not a leap year.");
}
Console.WriteLine(message);
}
}
}
namespace ICNumber
{
class Program
{
static void Main(string[] args)
{
Console.Write("Please enter your Singapore IC starting with T:");
string ICnumber = Convert.ToString(Console.ReadLine());
int totalsum = 0;
for (int k = 1; k < 8; k++)
{
int number = ICnumber.IndexOf(ICnumber, k);
int digitsum = 0;
if (k is 1)
digitsum = number * 2;
if (k is 2)
digitsum = number * 7;
if (k is 3)
digitsum = number * 6;
if (k is 4)
digitsum = number * 5;
if (k is 5)
digitsum = number * 4;
if (k is 6)
digitsum = number * 3;
if (k is 7)
digitsum = number * 2;
totalsum = totalsum + digitsum;
}
int validcheck = (totalsum + 4) % 11;
string Validcheck = Convert.ToString(validcheck);
int letter = ICnumber.IndexOf(ICnumber, 8);
string Letter = Convert.ToString(letter);
if (Validcheck == "0" && Letter == "J")
{
string validity = "Valid";
}
if (Validcheck == "1" && Letter =="Z")
{
string validity = "Valid";
}
if (Validcheck == "2" && Letter =="I")
{
string validity = "Valid";
}
if (Validcheck == "3" && Letter =="H")
{
string validity = "Valid";
}
if (Validcheck == "4" && Letter =="G")
{
string validity = "Valid";
}
if (Validcheck == "5" && Letter =="F")
{
string validity = "Valid";
}
if (Validcheck == "6" && Letter =="E")
{
string validity = "Valid";
}
if (Validcheck =="7" && Letter =="D")
{
string validity = "Valid";
}
if (Validcheck =="8" && Letter =="C")
{
string validity = "Valid";
}
if (Validcheck =="9" && Letter =="B")
{
string validity = "Valid";
}
if (Validcheck =="10" && Letter =="A")
{
string validity = "Valid";
}
else
{
string validity = "False";
}
string Validity = validity;
}
}
}
Why is it that i cant use the variable validity?
Because validity is local to the scope of the if's/else's. You can only use a variable inside of the curly brackets you define it in (by writing the datatype in front of the name). This is how to declare the variable in the function scope and then just reference if inside the if's and else's
namespace ICNumber
{
class Program
{
static void Main(string[] args)
{
Console.Write("Please enter your Singapore IC starting with T:");
string ICnumber = Convert.ToString(Console.ReadLine());
int totalsum = 0;
for (int k = 1; k < 8; k++)
{
int number = ICnumber.IndexOf(ICnumber, k);
int digitsum = 0;
if (k == 1)
digitsum = number * 2;
if (k == 2)
digitsum = number * 7;
if (k == 3)
digitsum = number * 6;
if (k == 4)
digitsum = number * 5;
if (k == 5)
digitsum = number * 4;
if (k == 6)
digitsum = number * 3;
if (k == 7)
digitsum = number * 2;
totalsum = totalsum + digitsum;
}
int validcheck = (totalsum + 4) % 11;
string Validcheck = Convert.ToString(validcheck);
int letter = ICnumber.IndexOf(ICnumber, 8);
string Letter = Convert.ToString(letter);
string validity=""; //declare the variable here
if (Validcheck == "0" && Letter == "J")
{
validity = "Valid";//remove the keyword string. If you use the keyword you create a new variable (different from the one above)
}
else if (Validcheck == "1" && Letter =="Z")
{
validity = "Valid"; //keep on referencing the variable everywhere you need it
}
else if (Validcheck == "2" && Letter =="I")
{
validity = "Valid";
}
else if (Validcheck == "3" && Letter =="H")
.
.
.
You need to declare the variable validity outside of your if blocks. Since C# has block level scoping, each of your string validity =... statements is actually declaring a different variable named validity that only exists within that scope. When you're declaring the validity variable alongside validCheck:
int validcheck = (totalsum + 4) % 11;
string Validcheck = Convert.ToString(validcheck);
string validity = string.Empty;
And then updating each of the assignments to not include the typename:
if (Validcheck =="7" && Letter =="D")
{
validity = "Valid";
}
Variables in C# have block scope. If you declare a variable inside the block body of an if statement, it will only exist there.
Declare your variable outside the if statements. There is also a logic error in your code - the else at the end is attached only to the last if, so in order for your approach to work, you would need to use else if for the intermediate ifs:
string validity = null;
if (Validcheck == "0" && Letter == "J")
{
validity = "Valid";
}
else if (Validcheck == "1" && Letter =="Z")
{
validity = "Valid";
}
else if (Validcheck == "2" && Letter =="I")
{
validity = "Valid";
}
else if (Validcheck == "3" && Letter =="H")
{
validity = "Valid";
}
else if (Validcheck == "4" && Letter =="G")
{
validity = "Valid";
}
else if (Validcheck == "5" && Letter =="F")
{
validity = "Valid";
}
// .... etc.
else {
validity = "False"
}
string Validity = validity;
All of those if statements are also extremely redundant and could be replaced with a single if statement with one large condition.
You keep declaring the variable validity all the time. Declare it once then assign it. Also make it bool
I'd also consider a pre declared array or dictionary of valid combinations so you can just look up what you have in a couple of lines of code.
You have to declare string validity 1st before :
string validity = "";
if (Validcheck == "0" && Letter == "J")
{
validity = "Valid"
}...
I am trying to ask the user to enter a number from 2-12. I want to use a loop to check if valid, but am having trouble only displaying the result once.
Console.WriteLine("Enter number between 2 and 12");
int x = int.Parse(Console.ReadLine());
bool isValid = true;
for(int p = 2; p < 13; p++)
{
if(p > x)
{
isValid = true;
}
else
isValid = false;
if(isValid == true)
{
Console.WriteLine("{0} is good", x);
}
else
Console.WriteLine("not valid");
}
Why you need loop to check value from range ?
Try like this
if(x>=2 && x<=12)
Console.WriteLine("{0} is good", x);
else
Console.WriteLine("not valid");
Why do you want to use a loop for this?
You could check if the number is between 2 and 12 by doing this instead:
int x = int.Parse(Console.ReadLine());
bool isValid = true;
if (x < 2 || x > 12)
{
isValid = false;
}
Otherwise, if you still want to do your loop, you can try this:
Console.WriteLine("Enter a number between 2 and 12");
int x = int.Parse(Console.ReadLine());
bool isValid = false;
for(int p=2; p<13; p++)
{
if(x == p)
{
isValid = true;
break;
}
}
if(isValid==true)
{
Console.WriteLine("{0} is good", x);
}
else
{
Console.WriteLine("not valid");
}
Edit:
Also just a suggestion but you should be careful with using Parse. If you use Parse and the user enters a non-numeric character or enters a number bigger/smaller than the allowed values for int, your app will stop with a FormatException error.
To fix this, you can use TryParse instead like this:
int x;
bool result = int.TryParse(Console.ReadLine(), out x);
if (result)
{
// Put your for loop or if statement here
}
else
{
Console.WriteLine("Error: Invalid number was detected.");
}
What are you trying to achieve? There's a flaw in the logic on the sample above, where you only ask once, and then loop 10 times. To simplify you can loop and then ask for the user input until 0 is entered and the loop will exit.
Sample:
static void Main(string[] args)
{
int x = 0;
do
{
Console.WriteLine("Enter number between 2 and 12. (0 to exit)");
x = int.Parse(Console.ReadLine());
if (x >= 2 && x <= 12)
{
Console.WriteLine("{0} is good", x);
}
else if(x != 0)
{
Console.WriteLine("{0} is not valid", x);
}
} while (x != 0);
}
Console.WriteLine("Enter number between 2 and 12: ");
int x = int.Parse(Console.ReadLine());
bool isValid = (2 <= x && x <= 12);
Console.WriteLine("{0} is {1}valid", x, isValid ? "" : "not ");
Here try this
static void Main(string[] args)
{
while (true)
{
Console.WriteLine("Enter number between 2 and 12");
int x = int.Parse(Console.ReadLine());
if (!Enumerable.Range(1, 12).Contains(x))
{
Console.WriteLine("{0} Its not Good\n",x);
}
else
{
Console.WriteLine("{0} Its Good\n",x);
break;
}
}
Console.WriteLine("Press any key to exit..");
Console.ReadKey();
}
If you're trying to validate if the number fall within the range 2-12 you should remove your loop and use this instead
bool isValid = true;
if (x < 2 || x > 12) {
isValid = false;
}
or simply
bool isValid = x >= 2 && x <= 12;
I've got an array with 90,000 integers and also have a txt file ,
I have to read the txt file sequentially and am not allowed to put it into an array , Foreach record in the text file
file I have to find the corresponding number in the array using binary search.then display how many matching numbers.
this is how I done it but it only finds the first matching number then stops
static void Main(string[] args)
{
//etc(OTHER CODE).......................
Array.Sort(NumFile);
// BINARY SEARCHHHH
int last,
first,
mid = 0,
target,
found = 0,
counter = 0;
string run;
//Stats
int Finds = 0;
first = 0;
last = NumFile.Length - 1;
//READ TextFile
StreamReader search = new StreamReader("Records.txt");
target = int.Parse(search.ReadLine());
//while (last >= first && found == 0)
while (last >= first && found == 0 && (run = search.ReadLine()) != null)
{
mid = (last + first) / 2;
if (target == NumFile[mid])
{
found = 1;
}
else
{
if (target < NumFile[mid])
{
last = mid - 1;
}
else
{
first = mid + 1;
}
}
if (found == 1)
{
Console.WriteLine("\nThe number was found at location {0}", mid);
Finds++;
}
else
{
//Console.WriteLine("\nNumber not found");
}
}
Console.WriteLine("Binary Search Statistics \t Hits:{0} ,hits);
} .
This is your while loop look at the while condition found == 0
while (last >= first && found == 0 && (run = search.ReadLine()) != null)
{
mid = (last + first) / 2;
if (target == NumFile[mid])
{
found = 1;
}
else
{
if (target < NumFile[mid])
{
last = mid - 1;
}
else
{
first = mid + 1;
}
}
if (found == 1)
{
Console.WriteLine("\nThe number was found at location {0}", mid);
Finds++;
}
else
{
//Console.WriteLine("\nNumber not found");
}
}
So inside where found == 1 if statement you need to make found to = 0 so it continues in the loop
if (found == 1)
{
Console.WriteLine("\nThe number was found at location {0}", mid);
Finds++;
found =0;
}