C# How to correct wrong input within an array - c#

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

Related

How can do calculations inside a string?

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

I can't get numbers to be output the way I want in C#

I want to input a number between 1-100 and the console should write all numbers from input number to 101. If I input a number that is between 1-100 the program should close. I am having trouble getting the program to close when I input 0 or 101. It either freezes or includes 0 if I input 0 and just writes 101 if 101 is input. When the numbers are output there is no space between them.
static void Main(string[] args)
{
Console.WriteLine("Input a number between 1-100");
Console.Write("");
string number = Console.ReadLine();
int x = Convert.ToInt32(number);
do
{
if (x > 0 || x < 101) //I tried switching out || for &&
{
Console.Write(x++);
}
} while (x != 102);
}
You can do this using a for loop with a predefined value.
for (int x = Convert.ToInt32(number); x < 102; x++)
{
Console.WriteLine(x);
}
if (x > 0 || x < 101)
this is true for pretty much every number. You want to change || to &&
Console.Write(x++);
Change this to WriteLine or add an extra space at the end of x++ to get your space between them.
while (x != 102);
this only checks a single value. if you typed in, for example, 103, you would get an infinity loop. try < 102
One way is to use the current value of x as loop-condition
Console.WriteLine("Input a number between 1-100");
int x = Convert.ToInt32(Console.ReadLine());
while (x > 0 && x < 101)
{
Console.WriteLine(x++);
}
I think it's better to use a "for" loop:
Console.WriteLine("Input a number between 1-100");
Console.Write("");
string number = Console.ReadLine();
int x = Convert.ToInt32(number);
if( x > 0 && x < 101 )
{
for( int i = x; i <=101; i++ )
{
Console.Write(i);
}
}
Or if you want to use "do-while" loop, change your code like this:
static void Main( string[ ] args )
{
Console.WriteLine("Input a number between 1-100");
Console.Write("");
string number = Console.ReadLine();
int x = Convert.ToInt32(number);
do
{
if (x > 0 && x <= 101)
{
Console.WriteLine(x++);
}
else
{
Environment.Exit( 0 ); // when insert 0 or 101
}
} while (x < 102);
Console.ReadKey( ); // when write all numbers, wait for a key to close program
}
This code also handles if user tries to give input that isn't a digit.
int x;
// read input until user inputs a digit instead of string or etc.
do
{
Console.WriteLine("Input a number between 1-100");
}
while (!Int32.TryParse(Console.ReadLine(), out x));
// exit from program if x isn't between 1 and 100
if (x < 1 || x > 100)
return;
// else count from given number to 101
for(int i = x; i < 101; ++i)
{
Console.WriteLine(i);
}

Ideal behavior for a constraint in online test c#

I want to know how to proceed if a console input is not met in a online test.
Like - 0 > x > 10
Sample question -
Please take two inputs from user and return the sum of the both.
Constraint -
0 < a < 10
2 < b <= 15
Below are solutions I have tried with their success rate.
Case 1:
int a = Convert.ToInt32(Console.ReadLine());
while (a < 1 || a > 9)
a = Convert.ToInt32(Console.ReadLine());
int b = Convert.ToInt32(Console.ReadLine());
while (b < 3 || b > 15)
b = Convert.ToInt32(Console.ReadLine());
Success - 35 %
Case 2
int a = Convert.ToInt32(Console.ReadLine());
if(a < 1 || a > 9)
Environment.Exit(0);
int b = Convert.ToInt32(Console.ReadLine());
if(b < 3 || b > 15)
Environment.Exit(0);
Success - 35 %
Case 3:
try
{
int a = Convert.ToInt32(Console.ReadLine());
if (a < 1 || a > 9)
throw new ArgumentException();
int b = Convert.ToInt32(Console.ReadLine());
if (b < 3 || b > 15)
throw new ArgumentException();
return a + b;
}
catch(ArgumentException ex)
{
Console.WriteLine(ex);
}
Success - 0%
Case 4: Without Constraint
int a = Convert.ToInt32(Console.ReadLine());
int b = Convert.ToInt32(Console.ReadLine());
return a + b;
Success - 95%
So what am I missing to get 100%
You would need to do a validation of some sort. Don't use an "Environment.Exit" because a while loop doesn't work like that. A while loop will continue until it returns "False" for example see the code below to validate digit input in the console.
while(!int.TryParse(someString, out int someInt))
{
Console.WriteLine("Your variable someString contains something other than numbers.");
}
Your code might look something like this.0 > x > 10
while(x < 0 || x > 10)
{
Console.WriteLine("Do this code.");
}
Constraints:
0 < a < 10
2 < b <= 15
Code:
int a;
int b; //Declare these outside the loop.
while(!(a > 0 && a < 10 && b > 2 && b <=15))
{
Console.WriteLine("Please Input a valid number for A.");
a = Console.ReadLine();
Console.WriteLine("Please Input a valid number for B.";
b = Console.ReadLine();
}
int sum = a + b;
Console.WriteLine($"The sum is {sum}.");

My Else if statement is not working properly what is the issue?

i am new in C# and understanding how the if statement works i wrote these code but there seems to be a problem with it.When i write something that is 50 or greater and less then 60 it says Passed but the else if statement is not working.Whenever i write something greater then 60 nothing happens my program closes.
Console.WriteLine("Please state your marks........");
string uservalue = Console.ReadLine();
int x = Convert.ToInt32(uservalue);
if (x >=50)
{
if ( x <= 59)
{
Console.WriteLine("You Passed");
}
}
else if (x >=60)
{
Console.WriteLine("Passed Grade B");
}
Console.ReadLine();
...
if (x >= 50 && x < 60) {
Console.WriteLine("You Passed");
}
else if (x >= 60) {
Console.WriteLine("Passed Grade B");
}
Console.ReadLine();
...
if (x >= 50) is a weaker condition than if (x >= 60). This means that if the former is true, then program control never considers the (x >= 60) case.
The solution here is to deal with the (x >= 60) case first.
You should swap the condition and the code should be as follows and would not require the additional condition check for <=59:
Console.WriteLine("Please state your marks........");
string uservalue = Console.ReadLine();
int x = Convert.ToInt32(uservalue);
if (x >=60)
{
Console.WriteLine("Passed Grade B");
}
else if (x >=50)
{
Console.WriteLine("You Passed");
}
Console.ReadLine();
Firstly, I suggest you to use int.TryParse instead of Convert.ToInt32, because the user may enter non-integer value. And fix the if condition like that;
string uservalue = Console.ReadLine();
int x;
if(!int.TryParse(uservalue,out x))
{
Console.WriteLine("Invalid Input ! ");
Console.ReadLine();
return;
}
if (x >= 50 && x < 60)
{
Console.WriteLine("You Passed");
}
else if (x >= 60)
{
Console.WriteLine("Passed Grade B");
}
Add to your first if statement && x < 60.
It should look line if (x >=50 && x < 60)

Can I execute only specific portion of nested if else in c#?

This is not the actual code but it's what I want to do.
for loop is must but the nested if else loop inside should be executed according to the value of count_final which can be random between 1 to 3.
Like if the value of count_final is 3, all if...else loop should be considered. but if the value of count_final is 2, then only if...(1st)else if and else part only be executed. And if count_final=1 then only if and else part is executed (not any else-if).
Thought of putting another if...else within every if...else and checking count_final, but what if I'm not getting values of count2 and count3 when count_final=1.
Same, when count_final=2, I'm not getting the value of count3.
Ask in comment if you don't understand my question.
int count_final=Session["abc"];
//count_final=1;
//count_final=2;
//count_final=3;
for(int i=1;i<=10;i++)
{
if ((count1 <= count5) && (count1 <= count6))
{
Label1.Text="Hello1";
}
else if (count2 <= count4 && count2 <= count6)
{
Label2.Text="Hello2";
}
else if (count3 <= count4 && count3 <= count5)
{
Label3.Text="Hello3";
}
else
{
Label1.Text="Hello1";
}
}
Seems you have collection of "conditions" where amount of executed conditions depend on value of finalCount.
var rules = new Func<string>[]
{
() => (count1 <= count5 && count1 <= count6) ? "Hello1" : null,
() => (count2 <= count4 && count2 <= count6) ? "Hello2" : null,
() => (count3 <= count4 && count3 <= count5) ? "Hello3" : null
};
Label1.Text = rules.Take(finalCount)
.Select(rule => rule())
.Where(result => result != null)
.DefaultIfEmpty("Hello1")
.First();
Of course this solution is assuming that finalCount is always 1, 2 or 3.
DefaultIfEmpty is playing role of last else - will be used all conditions fails.
if i understand right.. which is a little unlikely
just add more criteria to your ifs!
if ((count1 <= count5) && (count1 <= count6))
{
if (count_final == 3 || count_final == 2) Label1.Text="Hello1";
}
else if (count2 <= count4 && count2 <= count6)
{
if (count_final == 3) Label2.Text="Hello2";
}
else if (count3 <= count4 && count3 <= count5)
{
if (count_final == 3) Label3.Text="Hello3";
}
else
{
if (count_final == 3 || count_final == 1) Label1.Text="Hello1";
}
Remembering that from what I understood there will be loops in that can achieve nothing, eg, if count_final == 2 and its not less or equal to count5 or count6, nothing will happen, same as for count_final == 1, if it matches any of the first bits the last else wont happen.
I suggest extending the conditions of your else if statements:
int count_final=Session["abc"];
//count_final=1;
//count_final=2;
//count_final=3;
for(int i=1; i<=10; i++)
{
if ((count1 <= count5) && (count1 <= count6))
{
Label1.Text="Hello1";
}
else if (count_final >= 2 && count2 <= count4 && count2 <= count6)
{
Label2.Text="Hello2";
}
else if (count_final >= 3 && count3 <= count4 && count3 <= count5)
{
Label3.Text="Hello3";
}
else
{
Label1.Text="Hello1";
}
}
When count_final == 1 this will not try to evaluate count2, count3 or count4 (which I understand is a requirement) because && will not evaluate its right hand side when there is false on the left.
Is this what you are looking for? To use less if/else statements:
int count_final = Session["abc"]; // random between 1 and 3
for(int i=1; i <= 10; i++)
{
switch(count_final)
{
case 3:
Label1.Text="Hello1";
// no break; so all gets executed
case 2:
Label2.Text="Hello2";
case 1:
Label3.Text="Hello3";
default: Label1.Text="Hello1";
}
}

Categories