I'm trying to create a booking service and I've been stuck on this part for many hours and I just can't figure out what I'm doing wrong.
So I've got a Two Dimensional array and when trying to print out some stuff when testing and trying to figure out what's wrong, all I get is System.String[] which doesn't really make me any wiser. I want to be able to access the details in i.e. m_nameMatrix[0,0] to check whether the seat is reserved or not.
Here's a snippet from my form code:
private void UpdateGUI(string customerName, double price)
{
string selectedItem = cmdDisplayOptions.Items[cmdDisplayOptions.SelectedIndex].ToString();
rbtnReserve.Checked = true;
lstSeats.Items.Clear();
lstSeats.Items.AddRange(m_seatMngr.GetSeatInfoStrings(selectedItem));
}
And here are two methods from my 2nd class:
public string[] GetSeatInfoStrings(string selectedItem)
{
int count = GetNumOfSeats(selectedItem);
if (count <= 0)
{
return new string[0];
}
string[] strSeatInfoStrings = new string[count];
for (int index = 0; index <= count; index++)
{
strSeatInfoStrings[index] = GetSeatInfoAt(index);
}
return strSeatInfoStrings;
}
public string GetSeatInfoAt(int index)
{
int row = (int)Math.Floor((double)(index / m_totNumOfCols));
int col = index % m_totNumOfCols;
string seatInfo = m_nameMatrix.GetValue(row, col).ToString();
return seatInfo;
}
I'm not actually getting an exception so it might be my logical thinking that's been taking a hit due to hours and hours of trying to figure it out.
EDIT:
public void ReserveSeat(string name, double price, int index)
{
int row = (int)Math.Floor((double)(index / m_totNumOfCols));
int col = index % m_totNumOfCols;
string reserved = string.Format("{0,3} {1,3} {2, 8} {3, 8} {4,22:f2}",
row + 1, col + 1, "Reserved", name, price);
m_nameMatrix[row, col] = reserved;
}
This line:
for (int index = 0; index <= count; index++)
should be:
for (int index = 0; index < count; index++)
Why? Lets say I have an array with 2 objects in it. count would be 2. However, the indexes are 0 and 1. So you have to use a less than operator.
If you're getting "System.String[]" in your messagebox, it's because you're trying to print a string[] directly, rather than the various strings it contains:
string[] data = GetSeatInfoStrings("foo");
MessageBox.Show(data);
Instead, you need to show the contents of data:
string[] data = GetSeatInfoStrings("foo");
MessageBox.Show(string.Join("\n", data));
See here for the documentation.
Suppose you had a method called ReturnArray():
class Class2
{
public string[] ReturnArray()
{
string[] str = new string[] { "hello", "hi" };
return str;
}
}
If you called ReturnArray in your main class like this:
Class2 class2 = new Class2();
private void button1_Click(object sender, EventArgs e)
{
MessageBox.Show(class2.ReturnArray());
}
it will return System.String[] because MessageBox.Show(...) takes a string as an argument, in this case.
So you'll also get the same result by using MessageBox.Show(class2.ReturnArray().ToString());
Instead, you may want to do something like this:
Class2 class2 = new Class2();
private void button1_Click(object sender, EventArgs e)
{
string[] strArray = class2.ReturnArray();
listBox1.Items.AddRange(strArray);
}
Related
class Asient
{
private List<String> letras = new List<String> {
"A","B","C","D","E","F","G","H","J"};
private List<string> fila = new List<string> {
"1","2","3","4","5","6","7","8"};
private List<string> asientos= new List<string>();
public Asient(){
for (int i = 0; i < letras.Count; i++){
for (int n = 0; n < letras.Count; n++){
string sillaletra = letras[i] + fila[n];
asientos.Add(sillaletra);
}
}
}
public List<string> GetAsientos(){
return this.asientos;
}
}
class Mainn
{
static void Main(string[] args)
{
Asient sillas = new Asient();
sillas.GetAsientos();
}
}
And the code give me this runtime error:
Unhandled exception. System.ArgumentOutOfRangeException: Index was out of range.
Must be non-negative and less than the size of the collection. (Parameter 'index')
at System.Collections.Generic.List`1.get_Item(Int32 index)
at A05CINE.Asient..ctor() in D:\Users\x\x\x\x\x\c#\x\x\x.cs:line 15
at A05CINE.Mainn.Main(String[] args) in D:\Users\x\Desktop\x\x\x\c#\A05\x\x.cs:line 31
Does someone know how to fix that?
I tried using
asientos.Add(letras[i] + fila[n]);
string sillaletra = letras[i] + fila[n];
asientos.Add(sillaletra);
It seems, you are looking for Cartesian Join, i.e. you want List<string> to be
{ "A1", "A2", ..., "A8", "B1", ..., "B8", ..., "J8" }
If it's your case, you can put a simple Linq query for this:
using System.Linq;
...
public Asient() {
asientos = letras
.SelectMany(letter => fila.Select(digit => letter + digit))
.ToList();
}
You have more letters than numbers, add
private List<string> fila= new List<string>{"1","2","3","4","5","6","7","8","9"};
and it will work.
You are looping through the same length. Into your loop, both ends at position letras.Count, but list has not the same length.
Your loop should iterate over the length of each array like this:
for (int i = 0; i < letras.Count; i++)
{
for (int n = 0; n < fila.Count; n++)
{
//...
}
}
Note that the first array goes from 0 to letras.Count.
And second goes from 0 to fila.Count.
Now, each position is iterated.
E.g. If we have an array [1,2,3,4,6,7,8] then 1 then 2 then 3 then 4 are all consecutive but 6 is not, so that's the first non-consecutive number.
If the whole array is consecutive then return null .
The array will always have at least 2 elements 1 and all elements will be numbers. The numbers will also all be unique and in ascending order. The numbers could be positive or negative and the first non-consecutive could be either too. please help me finish this code i am new in programming. My code:
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace _2katas
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
var input = this.txtInput.Text;
var numarray = input.Split(',');
int firstValue = Convert.ToInt32(numarray[0]);
for (var i = 0; i < numarray.Length; i++)
{
if (Convert.ToInt32(numarray[i]) - i != firstValue)
{
lblPrint.Text = "";
}
else
{
lblPrint.Text = "";
}
if (this.rdbConsecutive.Checked == true)
{
lblKataRunning.Text = "Consecutive";
}
else if (this.rdbStripCleaning.Checked == true)
{
lblKataRunning.Text = "Strip Cleaning";
}
}
}
}
}
Let's extract a method:
Find the first element of an array that is not consecutive ...
If the whole array is consecutive then return null
We can implement it like this:
private static string FirstInconsecutive(string data) {
var array = data.Split(',');
if (array.Length <= 0)
return null; //TODO: what shall we return on empty array?
if (!int.TryParse(array[0], out int delta))
return array[0];
for (int i = 1; i < array.Length; ++i)
if (!int.TryParse(array[i], out int value) || value - i != delta)
return array[i];
return null;
}
Usage:
string result = FirstInconsecutive(txtInput.Text);
Please note int.TryParse which helps to return the right answer "ABC" on an input like "1, 2, 3, ABC, 4, 6, 7, 8" (user input txtInput.Text can contain any string)
A linq solution just for the fun of it:
static int? FindFirstNonConsecutive(IEnumerable<int> arr)
{
var nonConsecutiveInfo =
arr.Select((i, index) => new {Index = index, Delta = i - index})
.FirstOrDefault(t => t.Delta != arr.First());
return nonConsecutiveInfo?.Delta + nonConsecutiveInfo?.Index;
}
Note that this will only work finding non consecutive numbers in ascending order as per requirements.
Two numbers are not consecutive if the left ones + 1 <> the right one.
Check with something like this, note that you have to change your boundary checks:
for (var i = 0; i < numarray.Length - 1; i++)
{
if (Convert.ToInt32(numarray[i]) + 1 != Convert.ToInt32(numarray[i+1]))
Update your condition as below for loop and it will work. I would suggest you to have separate function so that it could be reusable if needed elsewhere in code.
Here start your loop from i = 1 and compare numarray[i-1] + 1 != numarray[i] values.
You can convert your sting[] to int[] with var numarray = input.Split(',').Select(x => Convert.ToInt32(x)).ToArray(); and use it with IsConsecutive(numarray) as per button1_Click code.
You can get first non-consecutive value with minor modification in return type and return statement as shown in GetFirstNonConsecutiveValue().
public bool IsConsecutive(int[] numarray)
{
for (int i = 1; i < numarray.Length; i++)
{
if (numarray[i-1] + 1 != numarray[i])
{
return false;
}
}
return true;
}
public int? GetFirstNonConsecutiveValue(int[] numarray)
{
for (int i = 1; i < numarray.Length; i++)
{
if (numarray[i-1] + 1 != numarray[i])
{
return numarray[i];
}
}
return null;
}
private void button1_Click(object sender, EventArgs e)
{
var input = this.txtInput.Text;
var numarray = input.Split(',').Select(x => Convert.ToInt32(x)).ToArray();
var nonConsecutiveValue = GetFirstNonConsecutiveValue(numarray);
if (nonConsecutiveValue != null)
{
// nonConsecutiveValue is first non consecutive value.
}
else
{
// sequence is consecutive.
}
}
One way to go.
string rawData = "1,2,3,4,6,7,8,9";
IEnumerable<int> data = rawData.Split(',').Select(v => Convert.ToInt32(v));
IEnumerable<int> all = Enumerable.Range(data.Min(), data.Max() - data.Min() + 1);
IEnumerable<int> diff = all.Except(data);
if (diff.Count() == 0)
{
return null;
}
return data.ElementAt(all.ToList().IndexOf(diff.First()))
NB Not thoroughly tested.
Just test diff for being empty to get the numbers are consecutive
I have a problem about my c# project. In the program I have a list
private static void FillData(List<Question> questions)
{
AddQuestion(questions,
"DotA isimli MOBA oyununun açılımı nedir? ",
2,
"Defense of the Arkham",
"Defence of the Ancients",
"Defense of the Ancients",
"Dance of the Architectures"
);
like that and i wanna make that list randomizely showned in every opening with shuffle. In the example my teacher used
private static void Shuffle(Soru[] array)
{
int length = array.Length;
for (int i = 0; i < length; i++)
{
int index = i + ((int) (_random.NextDouble() * (length - i)));
Soru soru = array[index];
array[index] = array[i];
array[i] = soru;
}
this and i wanna make that in Guid.NewGuid(). Can anyone help me with replacing that with Guid?
(edited from comments) This is what I tried so far:
private static void Shuffle(List<Question> List)
{
List = List.OrderBy(o => Guid.NewGuid().ToString()).ToList();
foreach (Question question in ....) { Console.WriteLine(question);
}
but I can't fullfill foreach loop. And yes I want to use Guid instead of random.
The problem is that you only modified the input parameter to hold a reference of another List. As it is not passed as reference, in the place where you have called it will hold the reference of the original List.
You could try this way:
private static void Shuffle(List<Question> List)
{
var randomOrderList = List.OrderBy(o => Guid.NewGuid().ToString()).ToList();
for (int i = 0; i < List.Count; i++)
{
List[i] = randomOrderList[i];
}
}
i M declaring an int type array and trying to print all its elements but it prints only last element .....give me the right code.....
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
int[] arr;
int range;
public Form1()
{
InitializeComponent();
}
private void textBox1_TextChanged(object sender, EventArgs e)
{
range = Convert.ToInt32(textBox1.Text);
arr = new int[range];
}
private void textBox2_TextChanged(object sender, EventArgs e)
{
for (int i = 0; i < range; i++)
{
arr[i] = Convert.ToInt32(textBox2.Text);
}
}
private void button1_Click(object sender, EventArgs e)
{
for(int i =0;i<range;i++)
{
textBox3.Text = textBox3.Text + arr[i].ToString();
}
}
}
}
This line: arr[i] = Convert.ToInt32(textBox2.Text); will set every element in the array to the value in textbox2. Is that your intent?
Int arrays are common. They store many integer values. And these values can be used in many ways. This introductory material covers int arrays, showing declarations, assignments, elements, loops and methods.please see here
this code is simple example that work array int
using System;
class Program
{
static void Main()
{
int[] arr1 = new int[] { 3, 4, 5 }; // Declare int array
int[] arr2 = { 3, 4, 5 }; // Another
var arr3 = new int[] { 3, 4, 5 }; // Another
int[] arr4 = new int[3]; // Declare int array of zeros
arr4[0] = 3;
arr4[1] = 4;
arr4[2] = 5;
if (arr1[0] == arr2[0] &&
arr1[0] == arr3[0] &&
arr1[0] == arr4[0])
{
Console.WriteLine("First elements are the same");
}
}
}
using System;
class Program
{
static void Main()
{
// Loop over array of integers.
foreach (int id in GetEmployeeIds())
{
Console.WriteLine(id);
}
// Loop over array of integers.
int[] employees = GetEmployeeIds();
for (int i = 0; i < employees.Length; i++)
{
Console.WriteLine(employees[i]);
}
}
/// <summary>
/// Returns an array of integers.
/// </summary>
static int[] GetEmployeeIds()
{
int[] employees = new int[5];
employees[0] = 1;
employees[1] = 3;
employees[2] = 5;
employees[3] = 7;
employees[4] = 8;
return employees;
}
}
Output
1
3
5
7
8
1
3
5
7
8
Is textBox2.Text one number, or a sequence of numbers? If it is, for example, 1,2,3 then you'll have to Split the string on , and then convert each entry of the String[] you get back to an integer, and store those in the array.
I am not sure what you are trying to do.
It appears that you are reading an input from a textbox whenever it is changed
and recreating the array to the size indicated in that textbox.
The second textbox fills the array whenever it is changed to whatever the second
textbox accepts as input (this makes no sense at all).
button1 displays array as a string, which is probably alright.
You might want to change the 2nd textbox into a button which fills the array.
Otherwise, rethink your intent of 2nd textbox, it makes no sense.
Where do you clear textBox3.Text ?
You are accumulating in this text box. When you do that, and the input overflows, you will only see the last thing added. Perhaps this is the problem. I might tweak:
private void button1_Click(object sender, EventArgs e)
{
textBox3.Text = "";
for(int i =0;i<range;i++)
{
textBox3.Text = textBox3.Text + arr[i].ToString();
}
}
I have an input as
2:{{2,10},{6,4}}
I am reading this as
string input = Console.ReadLine();
Next this input has to be passed to a function
GetCount(int count, int[,] arr)
{
}
How can I do so using C#?
Thanks
You could use RegularExpressions for extracting in an easy way each token of your input string. In the following example, support for extra spaces is included also (the \s* in the regular expressions).
Remember that always is a great idea to give a class the responsibility of parsing (in this example) rather than taking an procedural approach.
All the relevant lines are commented for better understanding.
Finally, i tested this and worked with the provided sample input strings.
using System;
using System.Text.RegularExpressions;
namespace IntPairArrayParserDemo
{
class Program
{
static void Main(string[] args)
{
var input = "2:{{2,10},{6,4}}";
ParseAndPrintArray(input);
var anotherInput = "2 : { { 2 , 10 } , { 6 , 4 } }";
ParseAndPrintArray(anotherInput);
}
private static void ParseAndPrintArray(string input)
{
Console.WriteLine("Parsing array {0}...", input);
var array = IntPairArrayParser.Parse(input);
var pairCount = array.GetLength(0);
for (var i = 0; i < pairCount; i++)
{
Console.WriteLine("Pair found: {0},{1}", array[i, 0], array[i, 1]);
}
Console.WriteLine();
}
}
internal static class IntPairArrayParser
{
public static int[,] Parse(string input)
{
if (string.IsNullOrWhiteSpace(input)) throw new ArgumentOutOfRangeException("input");
// parse array length from string
var length = ParseLength(input);
// create the array that will hold all the parsed elements
var result = new int[length, 2];
// parse array elements from input
ParseAndStoreElements(input, result);
return result;
}
private static void ParseAndStoreElements(string input, int[,] array)
{
// get the length of the first dimension of the array
var expectedElementCount = array.GetLength(0);
// parse array elements
var elementMatches = Regex.Matches(input, #"{\s*(\d+)\s*,\s*(\d+)\s*}");
// validate that the number of elements present in input is corrent
if (expectedElementCount != elementMatches.Count)
{
var errorMessage = string.Format("Array should have {0} elements. It actually has {1} elements.", expectedElementCount, elementMatches.Count);
throw new ArgumentException(errorMessage, "input");
}
// parse array elements from input into array
for (var elementIndex = 0; elementIndex < expectedElementCount; elementIndex++)
{
ParseAndStoreElement(elementMatches[elementIndex], elementIndex, array);
}
}
private static void ParseAndStoreElement(Match match, int index, int[,] array)
{
// parse first and second element values from the match found
var first = int.Parse(match.Groups[1].Value);
var second = int.Parse(match.Groups[2].Value);
array[index, 0] = first;
array[index, 1] = second;
}
private static int ParseLength(string input)
{
// get the length from input and parse it as int
var lengthMatch = Regex.Match(input, #"(\d+)\s*:");
return int.Parse(lengthMatch.Groups[1].Value);
}
}
}
Not to do your work for you, you will first have to parse the whole string to find the individual integers, either using regular expressions or, as I would do it myself, the string.Split method. Then parse the substrings representing the individual integers with the int.Parse or the int.TryParse methods.
I doubt you're going to get a serious parsing answer for your custom format. If you NEED to have the value inputted that way, I'd look up some info on regular expressions. If that's not powerful enough for you, there are some fairly convienient parser-generators you can use.
Alternatively, the much more realistic idea would be something like this:
(NOTE: Haven't tried this at all... didn't even put it in VS... but this is the idea...)
int rows = 0;
string rowsInput = "";
do {
Console.Write("Number of rows:");
rowsInput = Console.ReadLine();
} while (!Int32.TryParse(rowsInput, out rows);
int columns = 0;
string columnsInput = "";
do {
Console.Write("Number of columns:");
string columnsInput = Console.ReadLine();
} while (!Int32.TryParse(columnsInput, out columns);
List<List<int>> values = new List<List<int>>();
for (int i = 0; i < rows; i++)
{
bool validInput = false;
do {
Console.Write(String.Format("Enter comma-delimited integers for row #{0}:", i.ToString()));
string row = Console.ReadLine();
string[] items = row.split(',');
int temp;
validInput = (items.Length == columns) && (from item in items where !Int32.TryParse(item, out temp) select item).count() == 0;
if (validInput)
{
values.add(
(from item in items select Convert.ToInt32(item)).ToList()
);
}
} while (!validInput);
}