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
Related
How I take 2D array input in same line. in C# Console.ReadLine() allow us to take input one at a time .I want to take input as a row
int [,] arr = new int[m,n];
for(i = 0; i < m; i++)
{
for(j = 0; j < n; j++)
{
arr[i, j] = int.Parse(Console.ReadLine());
}
}
I want to take input this way
2 2,
10 20,
30 40
Entering a two-dimensional array on the command line is going to be error prone and frustrating for users. But if you MUST do it:
Figure out what symbols will separate values. (Commas, spaces?)
Figure out what symbols will separate array dimensions. (Pipes, perhaps? Whatever you choose, make sure it isn't the same symbol you use for separating values.)
Prompt the user for data and capture it into a string.
Validate the data.
Write a parser that parses your data into a multi-dimensional array.
I'd advise against trying to do this. But I don't dictate your requirements.
var delimiter = ' ';
for(var i = 0; i<n; i++) {
var row = Console.ReadLine();
var _arr = row.Trim().Split(delimiter);
for(var j=0; j<m; j++) {
arr[j, i] = int.Parse(_arr[j].Trim());
}
}
Update:
#mike-hofer, wholeheartedly agree with the "error prone and frustrating for users" characteristics of such way of input. I assume this is rather for a quick and dirty testing. Plus, exactly the same approach will be applied if you have to read the array from a file line by line, so there is some broader value in this question.
#rahi-ratul75, the code above does not do any error checking. The most likely error will be an entry which won't parse as an integer. You may want, therefore, to use int.TryParse(,) and, when false, ask to re-enter the line. The main logic, however, is there:
read the line
split it into an array
parse the entry into an integer
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++;
}
I have a list of potential sites to place landing pads in a 2d array. They're kept in 2 ints, one for row and one for column. I need to Randomly add a few landing sites from this list but for some reason it more often than not uses the same spots. I'd like to exclude these spots somehow so I used this loop but it locks up into an infinite loop for some reason and I just can't figure out why!
for(int j = 0; j < amountLandingPads; j++)
{
int r = Random.Range(0,potSitesC.Length-1);
while(roomType[potSitesR[r],potSitesC[r]] == (int)room.Landing)
{
r = Random.Range(0,potSitesC.Length-1);
}
roomType[potSitesR[r],potSitesC[r]] = (int)room.Landing;
//do more stuff
}
To me it looks like if the current site is already designated as a landing site, randomly choose another until you find a site that isn't a landing pad, what am I doing wrong?
potSites.Length is always gonna be 20+ and ammountLandingPads is always potsites.Length/4 and minimum 1.
roomtype is the type of room at that position (in a 2d int array)
It looks like you're using the same int r and also potSitesR.Length to decide both the row-coord and the column-coord of the landing site. This will end up always selecting positions from both potSitesR and potSitesC with the same indices, i.e. (potSitesR[1], potSitesC[1]), or (potSitesR[2], potSitesC[2]), and so on... and always within the potSitesR.Length range.
Try using a different value for both for more randomization. Here's example code:
for(int j = 0; j < amountLandingPads; j++)
{
//In the following statement
//Removed -1 because int version is exclusive of second parameter
//Changed it to potSitesR.Length (from potSitesC.Length)
int r = Random.Range(0, potSitesR.Length);
//second randomized number for column-randomization.
int c = Random.Range(0, potSitesC.Length);
while (roomType[potSitesR[r],potSitesC[c]] == (int)room.Landing) //using both randomized numbers
{
r = Random.Range(0, potSitesR.Length); // r from potSitesR.Length
c = Random.Range(0, potSitesC.Length); // c from potSitesC.Length
}
roomType[potSitesR[r], potSitesC[c]] = (int)room.Landing;
//do more stuff
}
I hope that helps!
I'm attempting to make a board that allows movement based on input similar to chess using c# and visual studio. I'm not sure if this is the best way to go about it but I'm trying to use a 4x4 2d array to map out a grid with place values that can be modified. The focus of my question is how do I print a full grid out with a loop that follows the 4x4 graph build where not only row "a" and column "1" placeholders show array values. Also would it be wise to use a 2d array to map out a board with values on every space or would it be easier to manually make a board and assign values to each array withing the manually drawn board. This is a console project, I'm only looking for the basis of the code for now, and my overall goal is something similar to the board game risk. I should add I'm a bit new to programming and any advice on what i should use and shouldn't use throughout is helpful. I've marked off original code I planned on using where x and y would use loops to make "[]" to show a graph after realizing it wouldn't mark every placeholder of the 4x4 graph.
class game
{
int[,] board;
string y;
int x;
static void Main(string[] args)
{
//for (int y = 0; y < 6; y++)
{
// Console.Write("[]");
}
//for (int x = 0; x < 6; x++)
{
// Console.WriteLine("[]");
}
int[,,] map = new int[,,]{
{
{0,0}, {1,0}, {2,0}, {3,0},
{0,1}, {1,1}, {2,1}, {3,1}
}
};
foreach (var item in map)
{
Console.Write("[" + item.ToString() + "]");
}
Console.ReadKey();
}
}
I tried to make this as effecient as possible while writing this.
So something like this:
int[,,] map = new int[,,]{
{
{0,1,2,3},
{0,1,2,3},
{0,1,2,3},
{0,1,2,3}
}
};
int width = map.GetLength(0);
int height = map.GetLength(1);
for(int i=0;i < width;i++)
{
for(int j=0;j < height;j++)
{
Console.Write("[" + map[i,j] + "]");
}
Console.Write("\n");
}
The \n signifies a new line in C#. Everytime you drop finish an array in a dimension it prints a new line.
I prefered to use for instead of foreach because it is faster for such cases. Foreach is for objects, For is for more mathematical issues.
Of couse you can change it as you see fit.
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.