i have got questions.
my problem is The user is asked to enter 20 exam grades. If the grades entered are less than 0 or greater than 100, you should be asked to enter again. How can I do that?
int not;
bool test = true;
for (int i = 0; i < 20; i++)
{
Console.Write((i + 1) + (".Not:"));
not = Convert.ToInt32(Console.ReadLine());
if (not < 0 || not > 100)
{
test = false;
Console.Write("Try again!");
}
else
{
test = true;
}
}
I want to use bool while doing this. would be glad if you help. thank you in advance
i changed code but i used goto. I dont want use to goto. How can i use bool doing this ?
int not;
int temp = 0;
for (int i = 0; i < 20; i++)
{
Console.Write("Add Not : ");
backtoAdd:
not = Convert.ToInt32(Console.ReadLine());
if (not < 0 || not > 100)
{
Console.WriteLine("Try Again!");
goto backtoAdd;
}
Console.WriteLine((i+1)+". Not : "+not);
temp = temp + not;
}
Console.Write("sum of not : "+temp);
Console.ReadKey();
As you mentioned it can be done with a while loop and condition to stop the loop. You can simplify it, I have added comments in the code example:
// declarations
int counter = 0;
int maxExamGradesInputCount = 20;
int highestGrade = 100;
int lowestGrade = 0;
// as long as counter is not equal to maxExamGradesInputCount continue
while (counter != maxExamGradesInputCount)
{
// we give input
string? input = Console.ReadLine();
// we try to parse our input
var parsed = int.TryParse(input, out var grade);
// if our input is parsed correctly
if (parsed)
{
// we check if the input value between the given range
if (grade < lowestGrade || grade > highestGrade)
{
Console.WriteLine("Try Again!");
}
else
{
// if with in range count
counter++;
}
}
}
Related
This function accepting input and telling the user whether the input is number or not a number.
static string isnum()
{
Console.WriteLine("Write a number please");
string a = Console.ReadLine();
string nums = "123456789";
int cnt = 0;
for (int i = 0; i < a.Length; i++)
{
for (int j = 0; j < nums.Length; j++)
{
if (a[i] == nums[j])
{
cnt++;
break;
}
}
}
if (cnt == a.Length)
{
Console.WriteLine(a + " is a number");
return a;
}
else
{
Console.WriteLine(a + " is not a number");
return "";
}
}
isnum();
I would like this function to repeat herself if the input is not a number, till the input will be a number, and then to stop.
This function working now, but she's working only one time.
When I'm trying to add a while block to the function to make her run again and again till the input is number I'm getting the "not all code paths return a value" error.
is it because a "return" statement ends a function, and therefore prevent her to run again?
how can I solve that?
Thank you very much!
You can fix this with creating a loop arround it and do not return when it's not a number.
static string isnum()
{
// just loop forever.
while (true)
{
Console.WriteLine("Write a number please");
string a = Console.ReadLine();
string nums = "123456789";
int cnt = 0;
for (int i = 0; i < a.Length; i++)
{
for (int j = 0; j < nums.Length; j++)
{
if (a[i] == nums[j])
{
cnt++;
break;
}
}
}
if (cnt == a.Length)
{
Console.WriteLine(a + " is a number");
return a;
}
else
{
Console.WriteLine(a + " is not a number");
// don't return here
}
}
}
In this case the best approach is to use do while because you want your code to at least run once.
you have one problem in your code which is returning when variable is not a number. see these modifications:
static string isnum()
{
do{
Console.WriteLine("Write a number please");
string a = Console.ReadLine();
string nums = "123456789";
int cnt = 0;
for (int i = 0; i < a.Length; i++)
{
for (int j = 0; j < nums.Length; j++)
{
if (a[i] == nums[j])
{
cnt++;
break;
}
}
}
if (cnt == a.Length)
{
Console.WriteLine(a + " is a number");
return a;
}
else
{
Console.WriteLine(a + " is not a number");
}
}while(true);
}
Call it in a while loop, and loop until the result is a number:
string result = "";
while (result == "")
{
result = isnum();
}
Console.WriteLine("result is a number: " + result);
Instead of looping you can try querying the a string with a help of Linq:
using System.Linq;
...
static string isnum() {
// Keep asking user until he/she provides a number
while (true) {
Console.WriteLine("Write a number please");
string a = Console.ReadLine();
// Number is
// 1. Has at least one character
// 2. All characters of number are digits
if (a.Length > 0 && a.All(c => c >= '0' && c <= '9')) {
Console.WriteLine($"{a} is a number");
// we have a proper number, let's return int
return a;
}
Console.WriteLine($"{a} is not a number");
}
}
This question already has answers here:
C# How to loop user input until the datatype of the input is correct?
(4 answers)
Closed 3 years ago.
I have a function which asks for input from the user which will be parsed to an int and that will be used to create a pyramid.
I know I have to use a loop of some kind and I have tried a do/while loop but I don't seem to understand it. I can't declare n above the Console.Write outside the do/while and if I have it below inside of the do/while, the while condition wont accept it because it's out of the scope. It would seem so simple to say, do(ask for input and assign to n) while(n <=0), but I can't do that.
I also had an idea I tried which was to run the function within itself as long as n was <=0 but that runs the function infinitely. Not sure if I'm on the right track but I feel lost right now.
static void Pyramid()
{
Console.Write("Choose a pyramid height: ");
int n = Int32.Parse(Console.ReadLine());
for (int i = 0; i < n; i++)
{
for (int j = 0; j < n - 1 - i; j++)
{
Console.Write(" ");
}
for (int j = 0; j < i + 2; j++)
{
Console.Write("#");
}
Console.Write(" ");
for (int j = 0; j < i + 2; j++)
{
Console.Write("#");
}
Console.WriteLine();
}
}
It should works:
int n;
do
{
Console.Write("Choose a pyramid height: ");
n = Int32.Parse(Console.ReadLine());
if ( n <= 0) Console.WriteLine("Value must be greater than 0.");
}
while ( n <= 0 );
Just use an infinite while loop, and continue if the number is invalid:
static void Pyramid()
{
while(true)
{
Console.Write("Choose a pyramid height: ");
int n = Int32.Parse(Console.ReadLine());
if (n <= 0)
{
Console.Error.WriteLine("That's an invalid number");
continue;
}
for (int i = 0; i < n; i++)
{
for (int j = 0; j < n - 1 - i; j++)
{
Console.Write(" ");
}
for (int j = 0; j < i + 2; j++)
{
Console.Write("#");
}
Console.Write(" ");
for (int j = 0; j < i + 2; j++)
{
Console.Write("#");
}
Console.WriteLine();
}
}
}
Let's extract method. We should implement 2 checks:
If input is an integer value at all (e.g. "bla-bla-bla" is not an integer)
If input is a valid integer (we don't accept -123)
Code:
public static int ReadInteger(string prompt,
Func<int, bool> validation = null,
string validationMessage = null) {
int result;
while (true) {
if (!string.IsNullOrEmpty(prompt))
Console.WriteLine(prompt);
string input = Console.ReadLine();
if (!int.TryParse(input, out result))
Console.WriteLine("Sorry, your input is not a valid integer value. Please, try again.");
else if (validation != null && !validation(result))
Console.WriteLine(string.IsNullOrEmpty(validationMessage)
? "Sorry the value is invalid. Please, try again"
: validationMessage);
else
return result;
}
}
then you can easily use it:
int n = ReadInteger(
"Choose a pyramid height:",
(value) => value > 0,
"Pyramid height must be positive. Please, try again.");
//TODO: your code here to draw the pyramid of height "n"
please, note, that you can easily restrict the upper bound as well (a pyramid of height 1000000000 will hang the computer):
int n = ReadInteger(
"Choose a pyramid height:",
(value) => value > 0 && value <= 100,
"Pyramid height must be in [1..100] range. Please, try again.");
Write a console application that calculates the sum of a given number of integers.
The numbers are entered one per line, and the application will read one by one until the user writes the character instead of a number. When the user has typed x, the application knows that all the numbers in the string have been entered and displays their amount.
If the first thing the user enters is the x character, the application will return 0.
Example:
For input:
2
5
-3
1
X
The console will display:
5
and this is my code
string[] answer = new string[10];
int sum = 0
for (int i = 0; i < answer.Length; i++)
{
sum += Int32.Parse(answer[i]);
if (answer[i] == "x")
{
Console.WriteLine(sum);
}
answer[i] = Console.ReadLine();
}
Console.Read();
Can anyone tell me why is not working?
First of all, the working code (I didn't focus on X but on any char that isn't a number):
int n;
int sum = 0;
while (int.TryParse(Console.ReadLine(), out n))
{
sum += n;
}
Console.Write(sum );
Console.ReadKey();
Secondly, your code doesn't work because your array is full of 'null'-s when you try to parse the content of its first cell in 'answer[i]'
Here's a dumb (a bit) fix for your code:
string[] answer = new string[10];
//HERE
for (int i = 0; i < answer.Length; i++)
{
answer[i] = "0";
}
int sum = 0;
for (int i = 0; i < answer.Length; i++)
{
sum += Int32.Parse(answer[i]);
if (answer[i] == "x")
{
Console.WriteLine(sum);
}
answer[i] = Console.ReadLine();
}
Console.Read();
Another problem with your code is you don't stop the iteration once "x" is entered, but continue until the end of the array (until it's been 10 times).
Here's kind of a complete fix for your code:
string[] answer = new string[10];
for (int i = 0; i < answer.Length; i++)
{
answer[i] = "0";
}
int sum = 0;
for (int i = 0; i < answer.Length; i++)
{
answer[i] = Console.ReadLine();
if (answer[i] == "x")
{
break;
}
sum += Int32.Parse(answer[i]);
}
Console.WriteLine(sum);
Console.Read();
Few issues:
I think order of your code instructions is not correct. First time when you parse your array element, its not yet initialized.
int sum = 0 is missing ; at the end.
You should always use TryParse instead of Parse
Try the following code:
string[] answer = new string[10];
int sum = 0, number;
for (int i = 0; i < answer.Length; i++)
{
answer[i] = Console.ReadLine();
if (answer[i] == "x")
{
Console.WriteLine(sum);
break;
}
if(Int32.TryParse(answer[i], out number))
sum += number;
}
I gave you your terminating 'x'
var answer = Console.ReadLine();
var sum = 0;
while (answer != "x")
{
if (Int32.TryParse(answer, out var value))
{
sum += value;
}
answer = Console.ReadLine();
}
Console.WriteLine(sum);
You should check for "x" first since int.Parse("x") throws exception:
Wrong order (current code):
sum += Int32.Parse(answer[i]); // <- this will throw exception on "x" input
if (answer[i] == "x") {
...
}
...
Right order:
if (answer[i] == "x") {
...
}
else
sum += Int32.Parse(answer[i]);
...
in order to check for syntax errors (e.g. when user inputs "bla-bla-bla") I suggest int.TryParse instead of int.Parse and let's get rid of the array why should we collect the items (esp. with unwanted restriction of 10 items)?
// long: we don't want overflow, e.g. 2000000000, 1000000000
long sum = 0;
while (true) {
// Trim() - let's be nice and allow user put leading/trailing spaces
string input = Console.ReadLine().Trim();
if (string.Equals("x", input, StringComparison.OrdinalIgnoreCase))
break;
if (int.TryParse(input, out var item))
sum += item;
else {
//TODO: Incorrect input, neither integer nor "x" (e.g. "abracadabra")
}
}
Console.WriteLine(sum);
Console.Read();
Everything is allright except the while statement.If you guys can help me that would be great.When the user write "Y" to do it again, he see: max value is: bla bla.
the user has to give a new positive number instead of to see the maximum value over and over again.
Console.WriteLine("Please give a positieve number. if you enter a negatieve number its not going to work");
int invoer = 0, max = 0;
string repeat = "";
do
{
for (int i = 1; invoer >= 0; i++)
{
Console.Write(i + "> ");
invoer = int.Parse(Console.ReadLine());
if (max < invoer)
{
max = invoer;
}
}
Console.WriteLine("Maximum value is: " + max);
Console.WriteLine("do you want to try again? y/n: ");
repeat = Console.ReadLine();
} while (repeat == "y" || repeat == "Y");
Im guessing at what this is supposed to be doing....
{
//Console.WriteLine("Please give a positive number. if you enter a negative number its not going to work");
int invoer;
int max;
string repeat;
do
{
//they have given a negative number and wish to try again
Console.WriteLine("Please give a positive number.\nIf you enter a negative number its not going to work");
invoer = 0;
max = 0;
repeat = "";
for (int i = 1; invoer >= 0; i++)
{
Console.Write(i + "> ");
invoer = int.Parse(Console.ReadLine());
if (max < invoer)
{
max = invoer;
}
}
Console.WriteLine("Maximum value is: " + max);
Console.WriteLine("do you want to try again? y/n: ");
repeat = Console.ReadLine();
} while (repeat == "y" || repeat == "Y");
}
I'm not 100% sure what you're trying to do, but it looks like you need to move your deceleration of invover and max into your do loop.
I need code, that takes inputs from user and then adds them together-simple. But I can't find a way, to take inputs until 0 is pressed and than add the numbers together..
So far, I made it take 10 values, but like I said it needs to be custom.. Thanks for your help.
int[] myarray = new int[10];
for (int i = 0; i < 10; i++)
{
myarray[i] = Convert.ToInt32(Console.ReadLine());
}
int a = 0;
for (int j = 0; j < 10; j++)
{
a = a + myarray[j];
}
Console.WriteLine(a);
Console.ReadLine();
The code below is not limited to 10 inputs, you can give as many input as you like
int sum=0, input;
do
{
input = Convert.ToInt32(Console.ReadLine());
sum += input;
}
while(input != 0);
Console.WriteLine(sum);
Console.ReadLine();
Check the input before adding it, and break out of the loop if it is 0:
int input = Convert.ToInt32(Console.ReadLine());
if(input == 0)
{
break;
}
myarray[i] = input;
As you don't know the length of the array, I'd recommend using a list. I've also added a tryparse to cope with dodgy user input. You can use Sum() on the list to avoid writing out another loop.
IList<int> myList = new List<int>();
string userInput = "";
int myInt = 0;
while (userInput != "0")
{
userInput = Console.ReadLine();
if(Int32.TryParse(userInput, out myInt) && myInt > 0)
{
myList.Add(myInt);
}
}
Console.WriteLine(myList.Sum());
Console.ReadLine();
When you have an unknown size array you should use a list.
var ls = new List<int>();
while(true)
{
var input = Convert.ToInt32(Console.ReadLine());
if(input == 0)
break;
ls.Add(input);
}
Lists by MSDN
You could use something like this :
while(true)
{
int input = Convert.ToInt32(Console.ReadLine());
if(input == 0)
break;
//do you math here
}