I am trying to write a program using a loop with a decrement and not to be able to use the same number twice. If using the same number, I would want a "invalid number" displayed. It is a number system set up to read numbers between 10 and 100. If it goes over 100, "invalid number" is displayed. This is what I have so far:
string userNumber;
int userNumberInt;
int previousNumber = 0;
for (int counter = 0; counter <= 10; counter++)
{
Console.WriteLine("Enter your number");
userNumber = Console.ReadLine();
userNumberInt = Convert.ToInt32(userNumber);
if ((userNumberInt <= 100) && (userNumberInt >= 10))
{
Console.WriteLine("Your number is " + userNumber);
previousNumber = userNumberInt;
}
else if
(previousNumber == userNumberInt)
{
Console.WriteLine("Number is invalid.");
}
// number is invalid
else
// number is valid
{
Console.WriteLine("Invalid number.");
counter--;
}
}
Console.ReadLine(); // for last enter key
}
}
}
With your use of previous, the same numbers could be entered. For example, the first number entered could be 12, so 12 becomes previousNumber. Then when you enter 12 again you'll display "invalid number" which is good, but you enter 13, then 13 becomes the previousNumber and now you can enter 12 again. So what you should do is store all of your valid numbers in a list and check if your userInput is in the list so that you're not using duplicate numbers.
public static void Main(string[] args)
{
List<int> validInputs = new List<int>();
for (int counter = 0; counter <= 10; counter++)
{
Console.Write("Enter a number: ");
string stringInput = Console.ReadLine();
int numberInput;
if (int.TryParse(stringInput, out numberInput))
{
if ((10 <= numberInput && numberInput <= 100) &&
validInputs.Contains(numberInput) == false)
{
Console.WriteLine("Number is valid");
validInputs.Add(numberInput);
}
else
{
// This is not a valid number cause it's not in the range or it's a duplicate
Console.WriteLine("Invalid number");
counter--;
}
}
else
{
// This is not a valid number
Console.WriteLine("Invalid number");
counter--;
}
}
}
Related
I am making a while loop. The purpose of the loop is to take all the positive numbers and calculating the average. It works most of the time but not always. Can someone help? here is the code:
double count = 0;
int sum = 0;
int input = -1;
while (input != 0)
{
Console.Write("Enter a number: ");
input = int.Parse(Console.ReadLine());
if (input > 0)
{
sum += input;
count++;
}
if (input < 0)
{
Console.Write("Enter a number: ");
input = int.Parse(Console.ReadLine());
}
}
if (input == 0)
{
Console.Write($"Average of all positive numbers is: { (sum += input) / count:0.00} ");
}
The second if is redundant it should work just like this
while (input != 0) {
Console.Write("Enter a number: ");
input = int.Parse(Console.ReadLine());
if (input > 0)
{
sum += input;
count++;
}
}
Your problem was when you enter a negative number it gives you the option to enter another, but then you enter a new iteration of the while loop and it asks you to enter another number. Removing the second if should fix your problem. Hope i helped :)
This code does not throw exceptions when non numeric data is entered
int count = 0;
long sum = 0;
int input;
Console.Write("Enter a number: ");
while (int.TryParse(Console.ReadLine(), out input))
{
Console.Write("Enter a number: ");
if (input > 0)
{
sum += input;
count++;
}
}
Console.Write($"Average of all positive numbers is: {sum} / {Math.Max(count,1.0)} = {Math.Round( sum / Math.Max(count,1.0), 2)}.");
I´m still very new to C#, we are supposed to use for-loops not methods. My question is how to limit values (1 to 25) that users puts in.
"The game" is supposed to ask a user to put in his values then it throw´s a random number and checks if it´s among numbers kept in myArray.
{
int[] myArray = new int[10];
Console.WriteLine("Write down your numbers");
for (int i = 0; i < 10; i++)
{
Console.WriteLine("Type in values for index nr {0}: ", i);
//user is asked to put in 10 values, what I need to do is to limit and
save as elements values in range between 1 and 25, so the loop continues (i++), if user types in a number that is outside that range my loop supposed to go a step back as if (i--)
myArray[i] = int.Parse(Console.ReadLine());
}
var rand = new Random(); //a random number is thrown
int rand1 = Convert.ToInt32(rand.Next(0, 25)); //random number ranges between 0 and 25
Console.WriteLine("{0}", rand1);
for (int i = 0; i < tal.Length; i++) //checking if random number is among users inputs
{
if (tal[i] == rand1)
{
Console.WriteLine("The random number {0} is among
your values", rand1);
}
else
{
Console.WriteLine("Random number isn´t among your
numbers");
break;
}
}
for (int i = 0; i < 10; i++)
{
Console.WriteLine("Type in values for index nr {0}: ", i);
if (int.TryParse(Console.ReadLine(), out int result) && result >= 0 && result <= 25)
{
myArray[i] = result;
}
else
{
i--;
Console.WriteLine("Wrong number!");
}
}
Your issue is that you try to maintain an index i that indicate your current position in the array.
One of the solution will be to simply drop it and add item to a collection till you have 10 items.
Here I took a HashSet<int> because we can't have duplicate in HashSet.
Any time you try to add one, it will simply drop it. But If you want to allow duplicate you can use a simple List<int>.
int collectionSize = 10;
int lowerBound = 1, upperBound = 25;
var userSelectedNumbers = new HashSet<int>();
while (userSelectedNumbers.Count() < collectionSize)
{
Console.WriteLine($"Enter an int between {lowerBound} and {upperBound} : ");
var input = Console.ReadLine();
if (int.TryParse(input, out int value)
&& lowerBound <= value
&& value < upperBound
)
{
userSelectedNumbers.Add(value);
}
else {
Console.WriteLine("Not a valid input!");
}
}
Console.Clear();
Console.WriteLine(
$"userSelectedNumbers contains {userSelectedNumbers.Count()} elements : {"
+ string.Join(", ", userSelectedNumbers) + "}"
);
You can then validate if the random numer is within the range using Contains :
var random = new Random();
int computerPick = random.Next(0, 25);
Console.WriteLine("Computer picked : " + computerPick);
if (userSelectedNumbers.Contains(computerPick))
{
Console.WriteLine("You win!");
}
else {
Console.WriteLine("You loose!");
}
Don't forget the using :
using System.Collections.Generic;
using System.Linq;
nb: The range is define using 1 ≤ x < 25, using W. Dijkstra convention http://www.cs.utexas.edu/users/EWD/ewd08xx/EWD831.PDF
First if works great
Second if throws an exception
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Enter a number and click enter, continue doing this process ");
Console.WriteLine("When you finish, just click enter without giving any input");
int i = 0;
int[] numbersArray;
List<int> numbersList = new List<int>();
while (true)
{
String numInput = Console.ReadLine();
numbersList.Add(Int32.Parse(numInput));
numbersArray = numbersList.ToArray();
if (i >= 1)
{
if (numbersArray[i] < numbersArray[i - 1])
{
Console.WriteLine("Your series is not going up!");
break;
Environment.Exit(0);
}
if (numbersArray[i] > numbersArray[i - 1])
{
if (numInput == "") {
break;
}
}
}
i++;
}
Console.WriteLine("You entered this series: ");
for (int j = 0; j < numbersArray.Length; j++)
{
Console.WriteLine(" " + numbersArray[j]);
}
Console.WriteLine("The length of the series youve entered is: " + numbersArray.Length);
}
}
You can't parse a string wihout digits like numInput = ""
EDIT: Try this code:
static void Main(string[] args)
{
Console.WriteLine("Enter a number and click enter, continue doing this process ");
Console.WriteLine("When you finish, just click enter without giving any input");
int i = 0;
int[] numbersArray = new []{1};
List<int> numbersList = new List<int>();
while (true)
{
String numInput = Console.ReadLine();
if (numInput == null || !numInput.All(char.IsDigit)) continue;
if (numInput != "")
{
numbersList.Add(Int32.Parse(numInput));
numbersArray = numbersList.ToArray();
if (i >= 1)
{
if (numbersArray[i] < numbersArray[i - 1])
{
Console.WriteLine("Your series is not going up!");
break;
Environment.Exit(0); // <-- Code is unreachable!
}
}
i++;
}
else if(i >= 1)
{
break;
}
}
Console.WriteLine("You entered this series: ");
foreach (int t in numbersArray)
{
Console.WriteLine(" " + t);
}
Console.WriteLine("The length of the series youve entered is: " + numbersArray.Length);
Console.ReadLine();
}
I assume you are trying to look at a index not existing.
Not sure of your language but I guess numbersArray[0] is the first index and numbersArray[1] is the second. So when you input your first number then you try to look at numbersArray[1] which doesn't exist.
I am writing a program that takes the scores of homework assignments, puts them in a array, then averages them. But I need to make it so that these grades range from 1-10. I am not sure how to make it only accept Numbers 1-10. Everything else is complete.
Here is what i have so far:
namespace AverageScore
{
class AverageScore
{
//prompt user to enter the size of the array
public int GetNum()
{
Console.WriteLine("Please enter how many scores you want to save!");
string strNum = Console.ReadLine();
int num = int.Parse(strNum);
return num;
}
static void Main(string[] args)
{
AverageScore scoreObject = new AverageScore();
int arraySize = scoreObject.GetNum();
//define a double array to save scores
double[] scoreArray = new double[arraySize];
string inValue = "";
double sum = 0,
intValue;
Console.WriteLine("Please enter all homework scores");
int counter = 0;
while (counter < arraySize)
{
inValue = Console.ReadLine();
while (double.TryParse(inValue, out intValue) == false)
{
Console.WriteLine("Invalid input = 0 stored in intValue");
inValue = Console.ReadLine();
}
sum += intValue;
scoreArray[counter] = intValue;
counter++;
}
Array.Sort(scoreArray);
double lowest= scoreArray[0];
double highest = scoreArray[arraySize-1];
sum = sum - lowest - highest;
double average = sum / arraySize;
Console.WriteLine("The average grade of the scores is" + average);
Console.WriteLine("The Lowest Score is" + lowest);
Console.WriteLine("The Highest Score is" + highest);
Console.Read();
}
}
}
so your problem is to restrict a input to 1-10 correct?
Why not just:
public int InputGrade()
{
Console.Clear();
Console.WriteLine("Please enter a grade [1-10]");
var grade = -1;
if (!Int32.TryParse(Console.ReadLine(), out grade))
return InputGrade();
if (grade < 1 || grade > 10)
return InputGrade();
return grade;
}
then you should be able to use it like this and it is cleaner:
while (counter < arraySize)
{
var grade = InputGrade();
sum += grade;
scoreArray[counter++] = grade;
}
recommendation
Indeed you should refactor the input from the calculation part - you code will get much more cleaner and more readable:
IEnumberable<int> InputGrades()
{
var count = GetNum();
var grades = new List<int>();
for (var i = 0; i < count; i++)
grades.Add(InputGrade());
return grades;
}
void OutputScores(IEnumerable<int> grades)
{
var scores = grades.Cast<doulbe>().ToArray();
var lowest = scores.Min();
var highest = scores.Max();
var average = scores.Average();
Console.WriteLine("The average grade of the scores is" + average);
Console.WriteLine("The Lowest Score is" + lowest);
Console.WriteLine("The Highest Score is" + highest);
}
Adjust the while loop condition to check that the number is in range (added a simple string format to present the previous invalid entry):
while (double.TryParse(inValue, out intValue) == false || intValue < 1.0 || intValue > 10.0**)
{
Console.WriteLine(String.Format("Invalid input = {0} stored in intValue", intValue));
inValue = Console.ReadLine();
}
This should do it:
while (counter < arraySize){
inValue = Console.ReadLine();
while (true){
if(double.TryParse(inValue ,out intValue) {
if(intValue >=1 && intValue <=10){
break;
}else{
Console.WriteLine("Input must be in the range 1-10");
inValue = Console.ReadLine();
}
}else{
Console.WriteLine("Invalid input = 0 stored in intValue");
inValue = Console.ReadLine();
}
}
sum += intValue;
scoreArray[counter] = intValue;
counter++;
}
Uses a loop to check if the value entered is correct:
while (int.Parse(inValue) < 1 || int.Parse(inValue) > 10) inValue = Console.ReadLine();
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.