passing an ArrayList by reference [closed] - c#

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Closed 8 years ago.
This question appears to be off-topic because it lacks sufficient information to diagnose the problem. Describe your problem in more detail or include a minimal example in the question itself.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Improve this question
So I have another assignment and I am attempting to use an ArrayList object to compile a list of last names, get a count, sort in ascending order, and then sort in descending order. The issue I'm having is that Visual Studio says there is an error when I go to compile/debug but nothing is flagging and I can't seem to figure out where the issue lies.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Collections;
namespace Lab5_exB
{
class Program
{
static void Main(string[] args)
{
string anotherList;
do
{
ArrayList lastNames = new ArrayList();
string exitValue;
do
{
Console.WriteLine("Enter a last name..");
exitValue = Console.ReadLine();
if (exitValue == "N" || exitValue == "n")
{
break;
}
lastNames.Add(exitValue);
} while (exitValue != "N" || exitValue != "n");
Console.WriteLine("Amount of last names entered: " + lastNames.Count);
lastNames.Sort();
Console.WriteLine("Last names in Ascending Alphabetical Order");
Console.WriteLine("------------------------------------------");
int i = 0;
while (i < lastNames.Count)
{
Console.WriteLine(lastNames);
i++;
}
lastNames.Reverse();
Console.WriteLine("Last names in Descending Alphabetical Order");
Console.WriteLine("-------------------------------------------");
int z = 0;
while (z < lastNames.Count)
{
Console.WriteLine(lastNames);
z++;
}
Console.WriteLine("Would you like to enter another list? (Y/N)");
anotherList = Convert.ToString(Console.Read());
}while (anotherList == "Y" || anotherList == "y");
Console.Read();
}
}
}
I have written my code using separate functions and by slapping it all together into a jumbled one method/function mess. Above is the mess. Here is the separate functions:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Collections;
namespace Lab5_exB
{
class Program
{
public static int GetLastNames(ArrayList lastNames, ref string exitValue)
{
do
{
Console.WriteLine("Enter a last name..");
exitValue = Console.ReadLine();
if (exitValue == "N" || exitValue == "n")
{
break;
}
lastNames.Add(exitValue);
} while (exitValue != "N" || exitValue != "n");
return 0;
}
public static int DisplayArrayNames(ArrayList lastNames)
{
Console.WriteLine("Amount of last names entered: " + lastNames.Count);
lastNames.Sort();
Console.WriteLine("Last names in Ascending Alphabetical Order");
Console.WriteLine("------------------------------------------");
int i = 0;
while (i < lastNames.Count)
{
Console.WriteLine(lastNames);
i++;
}
return 0;
}
public static int ReverseArrayNames(ArrayList lastNames)
{
lastNames.Sort();
lastNames.Reverse();
Console.WriteLine("Last names in Descending Alphabetical Order");
Console.WriteLine("-------------------------------------------");
int z = 0;
while (z < lastNames.Count)
{
Console.WriteLine(lastNames);
z++;
}
return 0;
}
static void Main(string[] args)
{
string anotherList;
do
{
ArrayList lastNames = new ArrayList();
string exitValue;
GetLastNames(lastNames);
DisplayArrayNames(lastNames);
ReverseArrayNames(lastNames);
Console.WriteLine("Would you like to enter another list? (Y/N)");
anotherList = Convert.ToString(Console.Read());
}while (anotherList == "Y" || anotherList == "y");
Console.Read();
}
}
}
When using different functions. I receive an error that " No overload for method 'GetLastNames' takes 1 arguments " which I don't see the issue with...it appears to be written fine. When written as one method/function there is no error shown but there is 1 build error...which I assume has something to do with the code in the first "function".
I was thinking that maybe the declared functions need to be set to a string but They were flagging because they didn't return a value and I don't think I can return an ArrayList.
Any ideas?
Edit: Changed my code a bit per another's recommendation. Still receiving the "unknown" 1 failed in the build.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Collections;
namespace Lab5_exB
{
class Program
{
public static ArrayList GetLastNames()
{
string exitValue;
var lastNames = new ArrayList();
do
{
Console.WriteLine("Would you like to enter another name? (Y/N)");
exitValue = Convert.ToString(Console.Read());
if (exitValue == "N" || exitValue == "n")
{
break;
}
Console.WriteLine("Enter a last name..");
lastNames.Add(Console.ReadLine());
} while (exitValue != "N" || exitValue != "n");
return lastNames;
}
public static void DisplayArrayNames(ArrayList lastNames)
{
Console.WriteLine("Amount of last names entered: " + lastNames.Count);
lastNames.Sort();
Console.WriteLine("Last names in Ascending Alphabetical Order");
Console.WriteLine("------------------------------------------");
int i = 0;
while (i < lastNames.Count)
{
Console.WriteLine(lastNames);
i++;
}
}
public static void ReverseArrayNames(ArrayList lastNames)
{
lastNames.Sort();
lastNames.Reverse();
Console.WriteLine("Last names in Descending Alphabetical Order");
Console.WriteLine("-------------------------------------------");
int z = 0;
while (z < lastNames.Count)
{
Console.WriteLine(lastNames);
z++;
}
}
static void Main(string[] args)
{
string anotherList;
do
{
var lastNames = GetLastNames();
DisplayArrayNames(lastNames);
ReverseArrayNames(lastNames);
Console.WriteLine("Would you like to enter another list? (Y/N)");
anotherList = Convert.ToString(Console.Read());
}while (anotherList == "Y" || anotherList == "y");
Console.Read();
}
}
}

Look at your method definition:
public static int GetLastNames(ArrayList lastNames, ref string exitValue)
It takes two parameters. You're trying to call it with GetLastNames(lastNames). You need to provide a variable for exitValue to the method when you call it.
That's totally aside from the actual logic.
Try this instead:
public static ArrayList GetLastNames()
{
var lastNames = new ArrayList();
do
{
Console.WriteLine("Enter a last name..");
exitValue = Console.ReadLine();
if (exitValue == "N" || exitValue == "n")
{
break;
}
lastNames.Add(exitValue);
} while (exitValue != "N" || exitValue != "n");
return lastNames;
}
Then call it with just GetLastNames(). You need to assign the result to a variable -- so you'd do this:
var lastNames = GetLastNames();
This takes the object created during the execution of the GetLastNames method and assigns it to a variable within the Main method.
That said, you should be using a generic collection (List<string>) instead of an ArrayList -- generic collections give you type safety. ArrayList is a hold-over from the .NET 1.1 days, before we had generics. For reference, the current version of the .NET Framework is 4.5.1. We've had generics since .NET 2.0, which came out almost a decade ago.

Related

my Distinct function is not working and i can't see why c#

The Distinct function is not working when it should. This is the input I am using:
one one two
Distinct
End
this is my whole code:
using System;
using System.Collections.Generic;
using System.Linq;
namespace Array.Processing
{
class Program
{
static void Main(string[] args)
{
string input = Console.ReadLine();
List<string> texts = input.Split(" ").ToList();
string text = Console.ReadLine();
int a = 0;
while (text != "END")
{
text = Console.ReadLine();
List<string> infos = text.Split(" ").ToList();
if (text == "Distinct")
{
texts = texts.Distinct().ToList();
}
if (text == "Reverse")
{
texts.Reverse();
}
if (infos[0] == "Replace")
{
if (texts.Count > int.Parse(infos[1]) && int.Parse(infos[1]) >= 0)
{
texts.RemoveAt(int.Parse(infos[1]));
texts.Insert(int.Parse(infos[1]), infos[2]);
}
else
{
a++;
}
}
}
for(int n = 0; n < a; n++)
{
Console.WriteLine("Invalid input!");
}
foreach (string info in texts)
{
Console.Write(info + " ");
}
}
}
}
and this is the output I am receiving:
one one two
I can't figure out why both "one" remains. Been looking at the code for over an hour so far and still nothing...
First you have
string input = Console.ReadLine(); // one one two
Next you have
string text = Console.ReadLine(); // Distinct
Next, first time inside the while you have
text = Console.ReadLine(); // End
At this point you check if (text == "Distinct") but by now its been overwritten to "End" so you never end up calling Distinct() on the list.

NullReferenceException? Why? [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed last year.
Improve this question
I try to calculate the total collective age of my passengers in calc_total_age() this works before I add a passenger and writes out "0". However when I add a passenger I get NullReferenceException, I have tried different things but I just can't wrap my head around what I'm doing. I need a little shove in the right direction and maybe and explanation of what the he** I am doing and I don't know what my GetAge() does either really I have tried to call it but it doesn't seem to work.
This is all my code:
using System;
using System.Linq;
using System.Text;
using System.Collections.Generic;
using System.Threading.Tasks;
class Program {
public static void Main (string[] args) {
//Console.Clear();
Console.WriteLine("Hi, welcome to the Buss-Simulator!");
Console.ReadKey();
var mybus = new Bus();
mybus.Run();
Console.ReadKey();
}
}
using System;
using System.Linq;
using System.Text;
using System.Collections.Generic;
using System.Threading.Tasks;
class Bus {
public int total_passengers = 0;
public Passenger[] info_passengers;
public int totalAge = 0;
public int totalSeats = 25;
public void Run()
{
info_passengers = new Passenger[25];
string [] menu = new string[]{"1. Pick up passenger.", "2. Show who's on the bus.", "3. Calculate total age of passengers"};
int MenuSelect = 0;
while (true)
{
Console.Clear();
Console.WriteLine("What do you want to do?");
Console.WriteLine();
Console.CursorVisible = false;
if (MenuSelect == 0)
{
Console.WriteLine(menu[0] + " ⭅");
Console.WriteLine(menu[1]);
Console.WriteLine(menu[2]);
}
else if(MenuSelect == 1)
{
Console.WriteLine(menu[0]);
Console.WriteLine(menu[1] + " ⭅");
Console.WriteLine(menu[2]);
}
else if(MenuSelect == 2)
{
Console.WriteLine(menu[0]);
Console.WriteLine(menu[1]);
Console.WriteLine(menu[2] + " ⭅");
}
var keyPressed = Console.ReadKey();
if(keyPressed.Key == ConsoleKey.DownArrow && MenuSelect != menu.Length -1)
{
MenuSelect++;
}
else if (keyPressed.Key == ConsoleKey.UpArrow && MenuSelect >= 1)
{
MenuSelect--;
}
else if (keyPressed.Key == ConsoleKey.Enter)
{
switch (MenuSelect)
{
case 0:
add_passengers();
break;
case 1:
print_passengers();
break;
case 2:
calc_total_age();
break;
}
}
}
}
public void add_passengers()
{
if (total_passengers == 25)
{
Console.WriteLine("\nBus is full!");
System.Threading.Thread.Sleep(2000);
return;
}
try
{
Console.WriteLine("\nType the name, age & gender of your passenger.");
Console.Write("\nName: ");
string name = Console.ReadLine();
Console.Write("\nAge: ");
int age = Convert.ToInt32(Console.ReadLine());
Console.Write("\nGender: ");
string gender = Console.ReadLine();
Passenger passenger = new Passenger(aName: name, aAge: age, aGender: gender);
Array.Resize(ref info_passengers, info_passengers.Length + 1);
info_passengers[info_passengers.Length - 1] = passenger;
}
catch (Exception e)
{
Console.WriteLine("\nFollow instructions.");
System.Threading.Thread.Sleep(2000);
return;
}
total_passengers++;
Console.WriteLine("You boarded 1 Passenger." + "\nThere are " + (totalSeats - total_passengers) + " seats left.");
System.Threading.Thread.Sleep(2000);
return;
}
public void print_passengers()
{
Console.WriteLine();
foreach (var i in info_passengers)
{
Console.WriteLine(i);
}
Console.ReadKey();
}
public void calc_total_age()
{
for (int i = 0; i < total_passengers; i++)
{
totalAge += info_passengers[i].age;
}
Console.WriteLine(totalAge);
Console.ReadKey();
}
}
using System;
using System.Linq;
using System.Text;
using System.Collections.Generic;
using System.Threading.Tasks;
class Passenger{
public string name;
public int age;
public string gender;
public Passenger(string aName, int aAge, string aGender)
{
name = aName;
age = aAge;
gender = aGender;
}
public override string ToString()
{
return string.Format($"This is {name}, {gender}, {age} years old.");
}
public int GetAge()
{
return age;
}
}
you don't need to resize info_passengers array since it is enough for total passangers. When you add an extra array cell, you add a passanger to the end of arry, but you still have the empty cells in the beginnig of array with null that are causing the exception.
so remove this code
Array.Resize(ref info_passengers, info_passengers.Length + 1);
and fix this
total_passengers++;
info_passengers[ total_passengers-1] = passenger;
and don't forget to remove total_passengers++; from here
Console.WriteLine("You boarded 1 Passenger." + "\nThere are " + (totalSeats - total_passengers) + " seats left.");
and add totalAge=0 in calc_total_age
public void calc_total_age()
{
totalAge=0;
for (int i = 0; i < total_passengers; i++)
{
totalAge += info_passengers[i].age;
}
and it is not a very good idea to hide errors in your catch blok. I would make it
catch (Exception e)
{
Console.WriteLine("\n Error!!! " + e.Message);
System.Threading.Thread.Sleep(2000);
return;
}
The answer to this one is very simple!
You declare:
public Passenger[] info_passengers;
This actually creates a pointer to a Passenger array, which (like all pointers) is initially null. It does not create the actual array itself.
When your code comes to call:
Array.Resize(ref info_passengers, info_passengers.Length + 1);
the method Resize expects the array parameter to point to an array. However, info_passengers is still null. So you get the exception.
I think all you need to do is to initialise info_passengers to an new empty array, like this:
public Passenger[] info_passengers = new Passenger[]();
and then I think it'll all work.

How do I search an int array vs a string array by comparing it to user input

How do I check if user input matches a number in an array?
I've learned to compare user input or search using a string array, however doing the same with an int array is not working for me.
zipCode[i] = 0;
int userZip = 0;
do
{
Console.WriteLine( "enter a 5 digit zip code to see if it is supported in our area." );
Console.WriteLine( );
Console.WriteLine( "Enter a 0 to exit the program" );
userZip = 0;
if ( userZip == zipCode[i] )
{
found = true;
if ( found )
{
Console.WriteLine( "We support zip code {0}", userZip ); ;
}
else
{
Console.WriteLine( "We do not support", userZip );
}
}
} while ( userZip != 0 );
Console.ReadLine( );
How do I check if user input matches a number in an array?
using System;
using System.Collections.Generic;
public class Program
{
static List<string> _zipCodes;
static Program()
{
_zipCodes = new List<string>() { "80205", "80225", "80210" };
}
static void Main(string[] args)
{
string userZip = string.Empty;
do
{
Console.WriteLine("enter a 5 digit zip code to see if it is supported in our area.");
Console.WriteLine();
Console.WriteLine("Enter a -1 to exit the program");
userZip = Console.ReadLine();
if (_zipCodes.Contains(userZip))//<---------------THAT WAY
{
Console.WriteLine("We support zip code {0}", userZip); ;
}
else
{
Console.WriteLine("We do not support zip code {0}", userZip);
}
} while (userZip != "-1");
}
}
How do I check if user input matches a number in an array?
I will answer this question, though I can't post an example using your sample code since it's incomplete and it's not exactly clear what it's supposed to do.
First, let's create a method that gets an integer from the user. This method will continually loop until the user enters a valid integer:
public static int GetIntFromUser(string prompt = null)
{
int input;
int row = Console.CursorTop;
int promptLength = prompt?.Length ?? 0;
do
{
Console.SetCursorPosition(0, row);
Console.Write(prompt + new string(' ', Console.WindowWidth - promptLength - 1));
Console.CursorLeft = promptLength;
} while (!int.TryParse(Console.ReadLine(), out input));
return input;
}
Now, we can use that method to get the zip code from the user:
int userZipCode = GetIntFromUser("Enter a 5 digit zip code to see if it's supported: ");
Now I'm assuming you have an array of zip codes that are supported. Perhaps something like:
private static int[] GetSeattleZipCodes()
{
return new []
{
98101, 98102, 98103, 98104, 98105, 98106, 98107, 98108, 98109, 98110,
98111, 98112, 98113, 98114, 98115, 98116, 98117, 98118, 98119, 98121,
98122, 98124, 98125, 98126, 98127, 98129, 98131, 98133, 98134, 98136,
98138, 98139, 98141, 98144, 98145, 98146, 98148, 98154, 98155, 98158,
98160, 98161, 98164, 98165, 98166, 98168, 98170, 98174, 98175, 98177,
98178, 98181, 98185, 98188, 98190, 98191, 98194, 98195, 98198, 98199
};
}
So, now we have an int user input, and an int[] of valid zip codes, so to see if the array of valid zip codes contains the user zip code, we can just use the Contains method:
int[] seattleZipCodes = GetSeattleZipCodes();
bool found = seattleZipCodes.Contains(userZipCode);
TheFastCat beat me, but:
using System;
using System.Collections.Generic;
namespace ConsoleApplication1
{
class Program
{
private static IEnumerable<string> zipCodes = new string[] { "90210", "94102", "98101", "80014" };
static void Main(string[] args)
{
Console.WriteLine("enter a 5 digit zip code to see if it is supported in our area, or '0' to exit");
do {
// Read next line
string userZip = Console.ReadLine().Trim();
// Exit program?
if (userZip == "0")
break;
// Validate input
if (userZip.Length != 5)
{
Console.WriteLine("ERROR: Zip code {0} is {1} characters; expected 5", userZip, userZip.Length);
continue;
}
int n;
bool isNumeric = int.TryParse(userZip, out n);
if (!isNumeric)
{
Console.WriteLine("ERROR: Zip code {0} must be numeric", userZip);
continue;
}
// Finally, see if our zip code matches a zip code in the list
bool found = zipCodes.Contains(userZip);
if (found)
{
Console.WriteLine("We support zip code {0}", userZip); ;
}
else
{
Console.WriteLine("We do not support " + userZip);
}
} while (true);
Console.WriteLine("Done: exiting program");
}
}
}
Note:
Initializing the list
Validating the input
Using IEnumerable.Contains() ... without necessarily messing with LINQ.
Use of "break" and "continue" to control the loop, without necessarily needing an extraneous variable.
An int array is Enumerable<int>, so you could just use Contains(): https://learn.microsoft.com/en-us/dotnet/api/system.linq.enumerable.contains?view=netframework-4.7.2
TheFastCat and Rufus L done great job.
I just want to add an example. Using 'var' datatypes makes things easy and durable as well in C#
This example demonstrates both 'int' and 'string' using var datatypes in both cases. Good luck haberjin.
static void Main(string[] args)
{
//var ZipCodes = new List<string>() { "04846", "40569", "76859","54896", "84623" }; // ZipCodes are stored as a string in a List
var ZipCodes = new List<int>() { 04846, 40569, 76859, 54896, 84623 }; // ZipCodes are stored as an int in a List
//var userZip = "";
var userZip = 0;
do
{
Console.WriteLine("Enter a 5 digit zip code to see if it is supported in our area.");
//userZip = Console.ReadLine(); // Enable to receive userZip as a string
userZip = int.Parse(Console.ReadLine()); // receive userZip as an int
if (ZipCodes.Contains(userZip))
{
Console.WriteLine("We support zip code {0}", userZip);
}
else
{
Console.WriteLine("We do not support", userZip);
}
//} while (userZip != "0");
} while (userZip != 0);
}

How can i get the total occurrence of letter K? [duplicate]

This question already has answers here:
Number of occurrences of a character in a string [duplicate]
(6 answers)
Closed 6 years ago.
I want to check on how many times does k appears. this is
what i have done so far and am not getting the results.
class Program
{
static void Main(string[] args)
{
int count = 0;
string str = "hnfdjkkedjjykukyukrtrnrkkkkt";
string l;
for (int i = 0; i < str.Length; i++)
{
l = str.Substring(1, 1);
if (l == "k")
{
count++;
}
}
Console.WriteLine("k appears " + count++ + " times");
Console.ReadKey();
}
}
You can try :
int count = str.Count(c => c=='k')
Hope this help :-)
You can go as simple as
using System;
using System.Linq;
public class Program
{
public static void Main()
{
string s = "aasfkkfasfas";
int count = s.Count(l => l== 'k');
Console.WriteLine(count);
}
}
Calling Substring for each letter is really not the best solution. Keep in mind that string implements IEnumerable so you can also do it like this:
using System;
public class Program
{
public static void Main()
{
string s = "aasfkkfasfas";
int count = 0;
foreach(char c in s)
{
if(c == 'k')
count++;
}
Console.WriteLine(count);
}
}
This is closer to your original solution.
You can also use RegEx (Regular Expressions) for that but it's kind of overkill for your use case.
It's found in the namespace System.Text.RegularExpressions (see MSDN).
Regex.Matches(text, pattern).Count
In your case, it would be
Regex.Matches("hnfdjkkedjjykukyukrtrnrkkkkt", "[k]").Count

Create a list of strings from A to BBB in C#

Morning all,
I have a simple question that I could do with some help with.
I need to create a list of strings that will start with A and finish at some other point e.g BBB, but I am not sure the best and fastest way of doing it.
Thanks in advance.
Ok as requested more information.
I need to create a simple way of creating a list of bays for a warehouse. This wareshouse can have a variable number of Aisles in it, a variable number of rows in each aisle and a variable number of bins for the row. So when the user comes to setup their particular warehouse they can specify the start letter of the Aisle and the end letter of the Aisle.
As you can now see the hardcoded list from A to ... isn't going to work.
No error checking (start number could be greater than end number in which case you would get an infinite loop) but the code works fine.
Hope you at least understand it before submitting it!
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace testList
{
class Program
{
static void Main(string[] args)
{
Console.Write((int)'A');
Console.Write((int)'Z');
Console.WriteLine("Whats the starting string?");
string start = Console.ReadLine().ToUpper();
Console.WriteLine("Whats the end string?");
string end = Console.ReadLine().ToUpper();
List<string> retVal = new List<string>();
retVal.Add(start);
string currentString = start;
while (currentString != end)
{
currentString = IncrementString(currentString);
Console.WriteLine(currentString);
retVal.Add(currentString);
}
retVal.Add(end);
Console.WriteLine("Done");
Console.ReadKey();
}
private static string IncrementString(string currentString)
{
StringBuilder retVal = new StringBuilder(currentString);
char endChar= currentString[currentString.Length - 1];
for (int x = (currentString.Length - 1); x >= 0; x--)
{
char c = currentString[x];
if (TryIncrementChar(ref c))
{
retVal[x] = c;
break;
}
else
{
retVal[x] = 'A';
if (x == 0)
{
retVal.Insert(0,'A');
}
}
}
return retVal.ToString();
}
private static bool TryIncrementChar(ref char currChar)
{
if (currChar != 'Z')
{
currChar++;
return true;
}
return false;
}
}
}

Categories