I'm working on a very simple tic tac toe project where I check if a user input is in an array (looking for an integer from 1 to 9) and, if not, I want to change an index to that user input. Below is code, don't know what I'm doing wrong. CallSquare() returns an int.
int [] numbersPlayed = {0,0,0,0,0,0,0,0,0};
int callResult;
int totalPlayed = 0;
while (totalPlayed != 10)
{
callResult = CallSquare();
foreach (int i in numbersPlayed)
{
if (numbersPlayed.Contains(callResult))
{
Console.WriteLine("\n\nError, number already in array");
break;
}
else
{
numbersPlayed.SetValue(callResult, i);
}
}
totalPlayed++;
}
Basically, what it does after input is giving me the Error message above, even though I type an integer between 1 and 9, and then, only changes the value in the index number I have entered on the first input (for example, if I enter 1 on the first input, it will only change the first index on following inputs). Help please?
Edit: what I'm trying to do is to keep a record of the numbers that have been played. I figured an array like that was the way to go, but if you have a better solution, I'm listening.
I think, you'd be better off using a List:
List<int> numbersPlayed = new List<int>();
int callResult;
int totalPlayed = 0;
while (totalPlayed < 10)
{
callResult = CallSquare();
if( numbersPlayed.Contains(callResult) )
{
Console.WriteLine("\n\nError, number already in array");
}
else
{
numbersPlayed.Add(callResult);
}
totalPlayed++;
}
Related
I'm pretty new to C# and want the users to be able to write in 5 numbers between 1 to 25. The issue I'm having is that I don't want the user to type a number over 25 or a number below 1.
Also this is a task for my studies and my teacher want us to use arrays so I'm not allowed to use List.
int[] usernum = new int[4];
for (int i = 0; i < usernum.Length; i++)
{
usernum[i] = Convert.ToInt32(Console.ReadLine());
}
Ok, to start off, some annotations to your code:
int[] usernum = new int[4]; // should be: new int[5];
for (int i = 0; i < usernum.Length; i++)
{
usernum[i] = Convert.ToInt32(Console.ReadLine()); // use int.TryParse instead
}
Now, I don't want to just give you the code, since this should obviously be a learning experience.
What you need to do, though is integrate a "validation" cycle. That means:
Read in string from user
Try to parse string to number
If that fails: back to 1.
Check if number < 1 or > 25
If so: back to 1.
If you are here, you passed both checks and can
set usernum[i] = number
Next "i"
Obviously, there are some slight variations in how you twist and turn your checks and arrange loops which are equally valid.
For example: You can decide if you want to check if number is inside bounds or if you want to check if the number is outside bounds and jump or not jump accordingly ...
Why int.TryParse instead of Convert.ToInt32?
There are some rule of thumbs that can spare you from severe headaches:
"Never trust user input"
"Do not use exceptions for control flow"
Using Convert here, breaks both.
For one, Convert.ToInt32 throws if the string does not represent an integer value (chars other than +-0..9, value > int.Max or < int.Min). So in using it, you trust the user to type in a valid integer. Not a good idea.
Then, it throwing means: the case, that a user (maybe just made a typo) did not provide valid input is controlling your flow to error handling. But this case is not at all "exceptional". In fact, you should expect it. int.TryParse makes this possible, in that it returns you a flag (boolean) that informs you about success or failure of the conversion attempt (instead of throwing).
Though I would recommend you to learn if else loop first https://www.w3schools.com/cs/cs_conditions.asp
here is the code if needed
int[] usernum = new int[4];
for (int i = 0; i < usernum.Length; i++)
{
var result = Console.ReadLine();
int currentResult;
if (!int.TryParse(result, out currentResult))
{
Console.WriteLine("Invalid input - must be a valid integer value");
i--;
continue;
}
if(currentResult < 1 || currentResult > 25)
{
Console.WriteLine("Invalid input - must be between 1 & 25");
i--;
continue;
}
usernum[i] = currentResult;
}
for-loop might not be the ideal solution for this use-case where you need to conditionally increment the index.
This should do the trick:
int[] userNumbers = new int[5];
int i = 0;
while (i < userNumbers.Length)
{
string rawInput = Console.ReadLine();
bool isNumberValid = int.TryParse(rawInput, out int inputNumber); // as suggested by #Fildor
if(isNumberValid && inputNumber >= 1 && inputNumber <= 25) // increment counter only if 1 <= input <= 25
{
userNumbers[i] = inputNumber;
i++;
}
}
I am in my second week of C# training, so I am pretty new to programming. I have to make a program that returns the smallest integer out of a series of random integer inputs. Once the input = 0, the program should break out of the loop. I am only allowed to use while and for loops. For some reason my program breaks out of loop after the second input and it looks like it doesn't even care if there is a "0" or not. Could you please see where I went wrong? I have been busting my head off with this. Sorry if this question has already been posted by somebody else but I did not find an answer to it anywhere.
PS: The zero input should be taken into account for the comparison.
So this is what I've got so far:
class Program
{
static void Main()
{
int i = 0;
int input = Int32.Parse(Console.ReadLine());
int min = default;
while (input != 0)
{
Console.ReadLine();
if (i == 0)
{
min = input;
break;
}
if (input < min && i !=0)
{
input = Convert.ToInt32(Console.ReadLine());
min = input;
}
i++;
}
Console.WriteLine(min);
}
First of all you will want to re-read the documentation for for- and while-loops. There are several useful pages out there.. e.g. for / while.
Problem
The reason why your loop breaks is that you initialize i with 0.
int i = 0;
Inside your loop you are using the if-statment to break the loop if the condition "i is 0" is met.
if (i == 0)
{
min = input;
break;
}
The input that the user has to provide each iteration of the loop is ignored by your program as you are never storing this kind of information to any variable.
while (input != 0)
{
Console.ReadLine();
// ...
}
Possible Solution
As a beginner it is helpful to tackle tasks step by step. Try to write down each of this steps to define a simple algorithm. As there are many solutions to this problem one possible way could be:
Declare minimum value + assign max value to it
Use a while loop and loop till a specific condition is matched
Read user-input and try converting it to an integer
Check whether the value is 0 or not
4.1. If the value is 0, go to step 8
4.2. If the value is not 0, go to step 5
Check whether the value is smaller than the current minimum value
5.1. If the value is smaller, go to step 6
5.2. If the value is not smaller, go back to step 3
Set the new minimum
Go back to step 3
Break the loop
End program
A program that handles the above steps could look like:
using System;
namespace FindMinimum
{
public class Program
{
static void Main(string[] args)
{
// Declare minimum value + assign initial value
int minValue = int.MaxValue;
// Loop until something else breaks out
while (true)
{
Console.WriteLine("Please insert any number...");
// Read io and try to parse it to int
bool parseOk = int.TryParse(Console.ReadLine(), out int num);
// If the user did not provide any number, let him retry
if (!parseOk)
{
Console.WriteLine("Incorrect input. Please insert numbers only.");
continue;
}
// If the user typed in a valid number and that number is zero, break out of the loop
if (parseOk && num == 0)
{
break;
}
// If the user typed in a valid number and that number is smaller than the minimum-value, set the new minimum
if (parseOk && num < minValue)
{
minValue = num;
}
}
// Print the result to the console
Console.WriteLine($"Minimum value: {minValue}.");
// Keep console open
Console.ReadLine();
}
}
}
Try This:
int input;
Console.Write("Enter number:");
input = Int32.Parse(Console.ReadLine());
int min = input;
while(true)
{
if (input == 0)
break;
if (min > input)
min = input;
Console.Write("Enter number:");
input = Int32.Parse(Console.ReadLine());
}
Console.WriteLine(min);
Console.ReadKey();
I hope it helps.
I'd like some help in getting this program to work. The user must first input upper and lower bounds for the int[] array. Next, they input what numbers to exclude from said array and display. I'm having trouble getting/understanding how to remove these numbers. Any help would be greatly appreciated. Thank you
Code:
Console.WriteLine("Please enter the first integer for the lower bound now");
int lower = int.Parse(Console.ReadLine()); //Uses user input for lower array bound
Console.WriteLine("Now enter the second integer for the upper bound");
int upper = int.Parse(Console.ReadLine()); //Uses user input for upper array bound
Console.WriteLine("Finally, enter the integers you do not want to see in the range");
int[] exNums = new int[] {int.Parse(Console.ReadLine()) }; //User enters number to exclude from range
int[] numbers = Enumerable.Range(lower, upper).ToArray();
Random r = new Random();
int range = 0;
try
{
for (int i = 0; i < 50; i++)
{
range = r.Next(lower, upper);
Console.Write(range + ",");
}
}
catch (ArgumentOutOfRangeException e)
{
Console.WriteLine("Upper bound cannot be lower than lower bound");
}
try
{
...
}
catch (ArgumentOutOfRangeException e)
{
Console.WriteLine("Upper bound cannot be lower than lower bound");
}
Alright. Please, PLEASE don't write code like this. Rather than searching for an exception, check the values yourself.
if (upper < lower)
{
Console.WriteLine("Upper bound cannot be lower than lower bound");
return;
}
Let's correctly generate the IEnumerable<int> of numbers to start with. Enumerable.Range takes a starting number and an entry count, not the upper bounds.
IEnumerable<int> allNumbers = Enumerable.Range(lower, (upper - lower) + 1);
Assuming we have a collection of numbers to exclude:
int[] numbersToExclude = ...;
We can simply use the .Except() method of LINQ to take out what we don't want.
IEnumerable<int> filteredNumbers = allNumbers.Except(numbersToExclude);
.ToArray(), .ToList(), or foreach the results of filteredNumbers as you wish afterwards.
Just in case there is so miscommunication from the question title, "Removing integers from int[] array", you cannot remove entries from a c# array. Once you set the size of an array (the number of items that array can hold) you cannot change it.
The only way to add and remove items from an array is to create an entirely new array and copy over the elements you want to keep.
There are, however, different data structures that can add and remove entries without all this data management on your end, most popular is List<>.
Maybe there's some reason you need to use Arrays rather than Lists but why not something like... (Java example)
int[] answers = new int[upper];
int index=0;
for (int lower; lower<=upper; lower++){
// if current value is within excluded numbers array, skip
if (Arrays.binarySearch(excludes, lower) >= 0){
continue;
}
else{
//add to the answers array
answers[index] = lower;
index++;
}
}
I´m working on some codes in C# for school. But there is this exercise that is huge headache.
This is it: I have to develope a code that allows the user to set a value (put in an x) for a 2D array (5x5) from the keyboard. This means that when running the program the user should be able to set one value inside the array, something like "I wana set an "x" in 2,5 and 3,1". I just have no clue how to do that. it´s been already two weeks but i can´t figure it out.
This is what i have so far (updated, thnx to all, specially BradleyDotNET for support):
int[,] data = new int[5, 5];
public void load()
{
string[] input = Console.ReadLine().Split('=');
string[] coordinates = input[0].Split(',');
int[] intCoordinates = coordinates.Select(s => int.Parse(s)).ToArray();
data[intCoordinates[0]][intCoordinates[1]] = int.Parse(input[1]);
}
public void view()
{
Console.WriteLine("Matrix created is:");
for (int i = 0; i <= 4; i++)
{
Console.Write("\n");
for (int j = 0; j <= 4; j++)
{
Console.Write(data);
}
}
Console.ReadKey();
}
static void Main(string[] args)
{
Program objeto = new Program();
objeto.load();
objeto.view();
Console.ReadKey();
Console.Clear();
I also have to add a feature to let the user add as many "x" to the matriz as he wants, but im planning to do that with a "switch".
So, How do you set values inside the 2d array from keyboard?
Update: The mistake i get here is in line 10, inside "data". It says "Incorrect index number inside []. 2 was expected"
You didn't specify the format the input, so I"ll make one up. If the input was "2,4=10" (meaning set element[2][4] to 10), the code would be:
string[] input = Console.ReadLine().Split('=');
string[] coordinates = input[0].Split(',');
int[] intCoordinates = coordinates.Select(s => int.Parse(s)).ToArray();
matrix[intCoordinates [0]][intCoordinates [1]] = int.Parse(input[1]);
This code has a few problems with it, there is no range validation and if the user enters anything other than an int, it will throw. I'll leave those as an exercise to you, but feel free to ask if you run into trouble.
To explain, we use Console.ReadLine to get a whole line of input. Then we break it on the '=' character to get our coordinates and desired value. We then split the coordinates on ',' to get the different indices.
You can't use strings as array indices, so we call Select to invoke the int.Parse() function on each string, returning us a new array of ints.
Finally, we use the parsed indices to index into matrix and set it to the parsed value from the input.
Something like this should help you.
public void load()
{
for (int i = 0; i <= 4; i++)
{
for (int j = 0; j <= 4; j++)
{
Console.WriteLine("enter value for {0},{1}", i, j);
matrix[i,j]= int.Parse(Console.ReadLine());
}
}
}
BTW, in your view method start the loop from 0 to 4
I'm trying to create a program where the size of array index and its elements are from user input.
And then the program will prompt the user to search for a specific element and will display where it is.
I've already come up with a code:
using System;
namespace ConsoleApplication1
{
class Program
{
public static void Main(String [] args)
{
int a;
Console.WriteLine("Enter size of index:");
a= int.Parse(Console.ReadLine());
int [] index = new int [a];
for (int i=0; i<index.Length;i++)
{
Console.WriteLine("Enter number:");
index[i]=int.Parse(Console.ReadLine());
}
}
}
}
The problem with this is that I can't display the numbers entered and I don't have any idea how to search for an array element.
I'm thinking of using if statement.
Another thing, after entering the elements the program should display the numbers like Number 0 : 1
Is this correct: Console.WriteLine("Number"+index[a]+":"+index[i]);?
And where should I put the statement? after the for loop or within it?
You're on the right track. Look carefully at how you stuffed values into the array, and you might find a clue about "how to search for an array element" with specific value. This is a core introductory algorithm, so no shortcuts! You need to find the answer on your own :-).
What is the last line Console.WriteLine(index[i]);? It seems like you are using the loop variable outside the loop.
To display entered numbers (ie. if I understand well, the numbers in the array), you have just to walk through the array like this:
for (int i = 0; i < index.length; i++)
{
Console.WriteLine(index[i]);
}
Since you want display numbers only after every number is entered, you may put this code only after finishing the loop where the user is entering the numbers:
// The user is entering the numbers (code copied from your question).
for (int i = 0; i < index.Length; i++)
{
Console.WriteLine("Enter number: ");
index[i] = int.Parse(Console.ReadLine());
}
// Now display the numbers entered.
for (int i = 0; i < index.length; i++)
{
Console.WriteLine(index[i]);
}
// Finally, search for the element and display where it is.
int elementToSearchFor;
if (int.TryParse(Console.ReadLine(), out elementToSearchFor))
{
// TODO: homework to do.
}
To search for a number, you can either walk through the array again and compare each element until finding a good one, or use Linq TakeWhile() method. (I suppose that your intent is not to use Linq, so I don't provide any further detail in this direction.)
You could use Array.IndexOf,
int a;
Console.WriteLine("Enter size of Array:-");
a = int.Parse(Console.ReadLine());
int[] array = new int[a];
Console.WriteLine("Enter the Elements of the Array:-");
for (int i = 0; i < array.Length; i++)
{
array[i] = int.Parse(Console.ReadLine());
}
Console.WriteLine("\nThe Elemets of the Array are:-");
for (int j = 0; j < array.Length; j++)
{
Console.WriteLine(array[j]);
}
Just try to break down what you've done and what you still need to do
Create a program where:
1) size of its array elements comes from user input (check)
2) array elements come from user input (check)
3) Prompt the user to search for a specific element (TODO)
4) Display where it is (TODO)
From the code you've written so far I would think you have most of what you need to do #3 & #4
An if statement may come into play when finding the location of the element the user specifies.