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.
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 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);
}
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
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;
}
}
}