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);
}
}
}
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;
}
}
The main part of my code is working, the only thing that doesn't work is the output of all its divisors. My result if it's not a prime should be like this:
Input -> 4
Output -> false 1 2 4
Console.WriteLine("Type your number: ");
int n = Convert.ToInt32(Console.ReadLine());
int a = 0, i;
for (i = 1; i <= n; i++)
{
if (n % i == 0)
{
a++;
}
}
if (a == 2)
{
Console.WriteLine("true");
}
else
{
Console.WriteLine("false" + i);
}
Console.ReadLine();
To print all the divisors, you'll need to gather them up in a collection of some sort – a list of integers, here.
In addition, all integers are divisible by 1, so you don't want to start there; neither do you want to end at n, since n % n == 0.
var divisors = new List<int>();
for (var i = 2; i < 2; i++)
{
if (n % i == 0)
{
divisors.Add(i);
}
}
if (divisors.Count == 0)
{
Console.WriteLine("true");
}
else
{
Console.WriteLine("false " + String.Join(" ", divisors));
}
Here is a working solution. You basically have to store your divisors somewhere or print them directly:
public static void Method(int n)
{
if (IsPrime(n))
{
Console.WriteLine($"{n} is a prime");
return;
}
var divisors = new List<int>();
for(var i = 1; i <= n; i++)
{
if (n % i == 0)
divisors.Add(i);
}
Console.WriteLine($"{n} isn't a prime");
Console.WriteLine($"The divisors are: {string.Join(", ", divisors)}");
}
public static bool IsPrime(int n)
{
for(var i = 2; i < n; i++)
{
if (n % i == 0)
return false;
}
return true;
}
From a brief inspection, there are two ways to generate the output. So far, you count the number of divisors, but neither store them nor write them to the output. You could replace
if (n % i == 0)
{
a++;
}
by
if (n % i == 0)
{
Console.WriteLine(i);
a++;
}
or store the divisors in a
List<int>
to generate the output afterwards.
I am currently having problems with this loop. It becomes an infinite loop and i get a stack overflow error. This is for a interest rate trade swap application. i is the length of the trade and l is the increasing index.
private void button1_Click(object sender, EventArgs e)
{
int outp = 0;
int i = int.Parse(tradeLength.Text);
string month = "January";
for (int l = 1; l <= i; l++)
{
Console.WriteLine("I iterated " + l + " Amount of times");
if (l == 1)
{
month = "January";
}
if (l == 2)
{
month = "February";
}
if (l == 3)
{
month = "March";
}
if (l == 4)
{
month = "Aprll";
}
if (l == 5)
{
month = "May";
}
if (l == 6)
{
month = "June";
}
if (l == 7)
{
month = "July";
}
if (l == 8)
{
month = "August";
}
if (l == 9)
{
month = "September";
}
if (l == 10)
{
month = "October";
}
if (l == 11)
{
month = "November";
}
if (l == 12)
{
month = "December";
}
else
{
month = "Null";
l = 1;
}
The cause is the final else:
if (l == 12) {
month = "December";
}
else { // <- if l != 12 (e.g. l == 1) restart the loop
month = "Null";
l = 1;
}
you want else if:
if (l == 1)
{
month = "January";
}
else if (l == 2)
{
...
}
...
else if (l == 12)
{
...
}
else {
month = "Null";
l = 1;
}
Edit: Another problem (see FKEinternet's comment) is a user input: if i is greater than 12 l never reaches it. You have to either validate the user input:
int i = int.Parse(tradeLength.Text);
if (i > 12)
i = 12; // or ask for other value
or use modular arithmetics:
for (int index = 1; index <= i; index++) {
int l = index % 12 + 1;
if (l == 1)
{
month = "January";
}
else if (l == 2)
...
else if (l == 12)
...
else
{
month = "Null";
l = 1;
}
}
It is not a very good idea to set the loop variable inside the loop. Like #stuartd pointed out, in your else line you set the loop variable to 1 and causing the loop to start all over again. Remove the l=1 line in your else block.
I presume you want to go to next year when i > 12. The way your code is made, when this happens, you get to loop forever, because "l" never reaches a number bigger than 12, it becomes 1 when it hits 13 and starts over.
To fix this, instead of
if (l == 1)
you want to use
if ((l % 12) == 1)
so your entire loop would be like this:
for (int l = 1; l <= i; l++)
{
Console.WriteLine("I iterated " + l + " Amount of times");
if ((l % 12) == 1)
{
month = "January";
}
if ((l % 12) == 2)
{
month = "February";
}
if ((l % 12) == 3)
{
month = "March";
}
if ((l % 12) == 4)
{
month = "Aprll";
}
if ((l % 12) == 5)
{
month = "May";
}
if ((l % 12) == 6)
{
month = "June";
}
if ((l % 12) == 7)
{
month = "July";
}
if ((l % 12) == 8)
{
month = "August";
}
if ((l % 12) == 9)
{
month = "September";
}
if ((l % 12) == 10)
{
month = "October";
}
if ((l % 12) == 11)
{
month = "November";
}
if ((l % 12) == 0)
{
month = "December";
}
{
PS = this is really not the right way to do this, I'm just using your own code and making the least amount of mods for it to work as intented. Good luck!
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...
So I need to do a array loop with students for class. The input has to be between 0-100 otherwise it doesn't accept the input from the user.
Console.WriteLine("How many students?");
int num1 = Keyboard.ReadInt();
int[] array = new int[num1];
Console.WriteLine("Give the student grades: ");
for (int i = 0; i < array.Length; i++)
{
int wrong;
wrong = Keyboard.ReadInt();
if (wrong > 0 && wrong <= 100)
{
array[i] = wrong;
}
else
{
while (wrong < 0 && wrong >= 100)
{
Console.WriteLine("Wrong input:");
wrong = Keyboard.ReadInt();
}
}
I think you just need to change && to ||:
while (wrong < 0 || wrong >= 100) ...
A number cannot be lower than zero and greater than 99 at the same time.
Your wrong variable can't be less then 0 and and bigger than 100 at the same time.
You should say: if wrong is less than 0 OR bigger than 100
That's why you need to use || instead of &&
Change your code like this :
while (wrong < 0 || wrong >= 100)
{
Console.WriteLine("Wrong input:");
wrong = Keyboard.ReadInt();
}
or you could change while to if here:
if (wrong < 0 || wrong >= 100)
{
Console.WriteLine("Wrong input:");
wrong = Keyboard.ReadInt();
}
or you could remove the whole block and use it in else statement in these two ways:
if (wrong > 0 && wrong <= 100)
{
array[i] = wrong;
}
else if(wrong < 0 || wrong >= 100)
{
Console.WriteLine("Wrong input:");
wrong = Keyboard.ReadInt();
}
or
if (wrong > 0 && wrong <= 100)
{
array[i] = wrong;
}
else
{
Console.WriteLine("Wrong input:");
wrong = Keyboard.ReadInt();
}