Unable to print whole list to console - c#

Keep getting the following message when printing a list on console.
System.Collections.Generic.List`1[System.Int32]
This is the console code. It is designed to generate a Fibonacci sequence of a given length. I have tried using the ToString() method, but that doesn't work either. I have built the algorithm in Java so i know that the issue, is fundamentally a C# problem. The issue is resolved if print i print the list elements individually, but i can't print the whole list.
class Program
{
public static void Main(string[] args)
{
Fibonacci fibo = new Fibonacci();
Console.WriteLine(fibo.getSequence(9));
Console.ReadLine();
}
}
class Fibonacci
{
public List<int> getSequence(int length)
{
List<int> results = new List<int>();
results.Add(1);
results.Add(1);
int counter = 0;
while (counter != length - 2)
{
int num1 = results[results.Count - 1];
int num2 = results[results.Count - 2];
results.Add(num1 + num2);
counter++;
}
return results;
}
}

You're returning a List<int>. To print it, you have to e.g. iterate over it
foreach(var i in fibo.getSequence(9)) {
Console.WriteLine(i);
}
Or you can use String.Join()
Console.WriteLine(String.Join(" ", fibo.getSequence(9)));

You are trying to print the object directly to console try iterating over list and print them wherever returned.
for (var item in returned)
Console.WriteLine(item)
if using a custom Type. keep in mind that you have defined its to string method.

Change your Main() to read:
public static void Main(string[] args)
{
Fibonacci fibo = new Fibonacci();
foreach(var element in fibo.getSequence(9))
{
Console.WriteLine(element);
}
Console.ReadLine();
}
Explanation
Look at what you're passing to Console.WriteLine() in your example. getSequence() is returning a list, so you're passing a list to WriteLine(). WriteLine will ToString() on the collection which, by default, will render out the type. If you pass it each individual element (int), it will call ToString() on each one and give you the number.
This is based on the assumption that you want a line per element. If not, look into using String.Join

Related

No input to the console for a certain period of time

I want to create a function which will return the matrix, but I have a problem with limit the time of put the data to console.
public static List<List<int>> CreateMatrix()
{
List<List<int>> matrix = new List<List<int>>();
List<int> row = new List<int>();
do
{
row = Array.ConvertAll<string, int>(Console.ReadLine().Split(" ", StringSplitOptions.RemoveEmptyEntries), int.Parse).OfType<int>().ToList();
matrix.Add(row);
} while (matrix[0].Count == row.Count);
return matrix;
}
I want to create a loop which will accept the row of numbers, but when nothing is put inside the row at least five seconds for example, then the loop should be break
Using one of the examples from This Post, I've created a simple example for you which will add items entered on the console to a List collection. Hopefully it will be a good starting point for you to be able to do what you need.
public static void Main()
{
int waitTimeInSeconds = 10;
List<string> matrix = new();
do
{
var task = Task.Factory.StartNew(Console.ReadLine);
var result = Task.WaitAny(new Task[] { task }, TimeSpan.FromSeconds(waitTimeInSeconds)) == 0
? task.Result : string.Empty;
if (!String.IsNullOrEmpty(result))
{
matrix.Add(result);
}
else
{
break;
}
} while (true);
if (matrix is not null)
{
Console.WriteLine($"# Items Added to Array: {matrix.Count}\n");
foreach (var m in matrix)
{
Console.Write(m);
}
}
}
Reviewing your code however, I'm not sure what you're trying to achieve in your while loop.
Your row variable looks to take the input of the console.ReadLine() and convert it to an integer, but you haven't considered if the input isn't of type integer, as if not, it will cause a System.FormatException.
Secondly, it seems like you're returning a list of list simply because that's the type which Array.ConvertAll().ToList() returns and you want a to return multiple values. I suspect you just want to return the list of values that you've read from the console instead.
Just some food for thought

C# Creating a list that takes user input and after prints the number from the list within a certain value range.(please explain how and why it works)

using System;
using System.Collections.Generic;
namespace exercise_69
{
class Program
{
public static void Main(string[] args)
{
List<int> numbers = new List<int>();
//creating a list called numbers
while (true)
{
int input = Convert.ToInt32(Console.ReadLine());
if (input == -1)
{
break;
}
numbers.Add(input);
}
//fills a list called numbers until user enters " -1 "
Console.WriteLine("from where");
int lownum = Convert.ToInt32(Console.ReadLine());
//lowest number to get printed
Console.WriteLine("where to");
int highnum = Convert.ToInt32(Console.ReadLine());
//highest number to get printed
foreach(int number in numbers)
{
if(lownum < number || highnum > number)
{
Console.WriteLine(numbers);
} //trying to filter the numbers and print them
}
}
}
}
Blockquote
the issue i am having is when i run the program the console just tells me this
"System.Collections.Generic.List`1[System.Int32]"
so my question is how do i properly filter or remove numbers from a list within a certain value ( not index )
the console just tells me this "System.Collections.Generic.List`1[System.Int32]"
That's because you did this:
Console.WriteLine(numbers);
numbers is a List<int>, it's a whole collection of numbers not just a single number. Console.WriteLine has many varaitions ("overloads") that know how to do all different kinds of things. It has a large quantity of specific variations for numbers, strings, etc and there is one variation that's like a "catch-all" - it accepts an object which means it can accept pretty much anything in the C# universe. The only thing it does with it, if you do manage to end up using this variation (overload), is call ToString() on whatever you passed in, and then print the string it gets back.
Because you passed a List<int> in, and Console.WriteLine doesn't have any variation that does anything cool with a List specifically, it means your passed-in List gets treated by the catch-all version of WriteLine; "call ToString on what was passed in and print the result". Because List doesn't have a very specific or interesting ToString() of its own, it just inherits a version of ToString() from object, the most simple root of all things in C#. Object's ToString() doesn't do very much - it just returns the type of the object which, in this case, is a "System.Collections.Generic.List`1[System.Int32]".. and that's why you see what you see in the console
Now that you know why your code is printing the type of the List, because you're passing in a List, can you see how to change it so you're passing in something else (like, e.g. an actual number you want to print) ?
Console.WriteLine(numbers);
^^^^^^^
this needs to be something else - can you work out what?

Using two parameters (string, int) to define a max number of specific characters in string output

I am not very experienced with C# and have got a task to develop a simple program that can take two parameters; one string and one integer. The string is to be returned, and the integer is supposed to define the max number of each specific character that is returned in the string, i.e.:
input: "aaabbbbc", "2" output: aabbc
input: "acc", "1" output: ac
I've tried looking at different collections like IEnumerator to help make the code easier to write, but as I'm not very experienced I can't sort out how to utilize them.
This is the code that I've written so far:
public static string TwoParameters()
{
Console.Write("Write some characters (i.e. 'cccaabbb'): ");
string myString = Console.ReadLine();
return myString;
Console.Write("Write a number - ");
int max = Convert.ToInt32(Console.Read());
}
public static void Counter(string myString, int max)
{
string myString = TwoParameters(myString);
foreach (char a in myString)
{
var occurences = myString.Count(x => x == 'a');
if (occurences > max)
max = occurences;
}
}
Errors I get when running:
CS0136: Local or parameter 'myString' cannot be declared in scope because of enclosing local scope.
CS1501: No overload for method 'TwoParameters' takes 1 arg.
CS1061: 'string' does not contain a definition for count.
CS0165: Use of unassigned local variable 'myString'.
CS7036: There is no argument given that corresponds to the required formal parameter 'myString' of 'Program.Counter(string, int)'
Any kind of pointers to what I'm doing wrong, suggestions to how I can improve my code and/or finish it up for the program to make the output will be hugely appreciated.
A string can be treated as an IEnumerable<char>. You can use LINQ to first group the characters then take only 2 from each group, eg :
var input="aaabbbbc";
var max=2;
var chars=input.GroupBy(c=>c)
.SelectMany(g=>g.Take(2))
.ToArray();
var result=new String(chars);
This produces
aabbc
This query groups the characters together with GroupBy and then takes only max from each group with Take. SelectMany flattens all the IEnumerable<char> returned from Take into a single IEnumerable<char> that can be used to create a string
This function would also respect the order within the string, so aabcabc, 2 would result into aabcbc:
static string ReturnMaxOccurences(string source, int count)
{
return source.Aggregate(new Accumulator(), (acc, c) =>
{
acc.Histogram.TryGetValue(c, out int charCount);
if (charCount < count)
acc.Result.Append(c);
acc.Histogram[c] = ++charCount;
return acc;
}, acc => acc.Result.ToString());
}
But you need also this little helper class:
public class Accumulator
{
public Dictionary<char, int> Histogram { get; } = new Dictionary<char, int>();
public StringBuilder Result { get; } = new StringBuilder();
}
This method iterates the whole string and save within a histogram the occurences of each character. If the value is lower than the desired max value it will be added to the result string, otherwise it simply steps over the character and continues with the next.
Pointers to what you are doing wrong:
you reset your given max to the counts in your string
you only handle "a"
your TwoParameters function has unreachable code
you try to declare a variable name again already providing it to the function as parameter
you do not build a string to output
Using Linq is probably somewhat overkill for your level of knowledge. This is a simpler Version of Oliver's answer - respecting order of letters as well:
public static void Main()
{
var input = "abbaaabcbcccd";
var max = 2;
// stores count of characters that we added already
var occurences = new Dictionary<char,int>();
var sb = new StringBuilder();
foreach (var c in input)
{
// add with a count of 0 if not yet encountered
if (!occurences.ContainsKey(c))
{
// if you want only "consecutive" letters not repeated over max:
// uncomment the following line that resets your dict - you might
// want to use a single integer and character instead in that case
// occurences.Clear(); // better use a single int-counter instead
occurences[c] = 0;
}
// add character if less then max occurences
if (occurences[c] < max)
{
sb.Append(c);
occurences[c]+=1;
}
}
Console.WriteLine(sb.ToString());
}
Output:
abbaccd

How to write a function that takes an integer as a parameter and calculates and returns the squared value

Ahoy! I have just started methods but I am a tad confused when it comes to methods with math. First post so be nice :) I'm aware I out in NumberToSquare way too many times!
Write a program that asks the user to enter a number. In your program write a function called SquareValue that takes an integer parameter and calculates the square of integer parameter and returns this squared value. Your program should take this returned square value and display it. An example of the output is:
Please enter a number to square: 8
/ 8 squared is: 64
What I have so far is not so comprehensible. I thought along a few different avenues and was unsure as to what to delete. Help please.
namespace SquareValue
{
class Program
{
static void Main(string[] args)
{
int number=NumberToSquare();
SquareValue(NumberToSquare * NumberToSquare);
string output;
Console.ReadKey();
}
public int SquareValue(NumberToSquare, NumberToSquare);
{
int result = NumberToSquare * NumberToSquare;
return result;
Console.WriteLine("{0} squared is "+result");
}
public int NumberToSquare()
{
Console.WriteLine("Please enter a number to square: ");
int NumberToSquare = Console.ReadLine();
return NumberToSquare;
}
}
I see no reason to over complicate this:
public int Square(int x)
{
return (x * x);
}
or
public int Square(int x)
{
return Math.Pow(x,2);
}
Or just use Math.Pow as it exists with 2 as the Power Of number.
You seem very green on programming and I'm not sure SO is a place to go to learn the basics, but I'll run through what you've done and explain what's going wrong.
Your original program concept is fine but there are many issues with basic syntax. I understand you mightn't be familiar with reading compiler errors so I'll explain the errors that I see just reading through the code...
You put a ; at the end of the SquareValue(..., ...) method which teeminates the declaration so the body in braces isn't part of the method, then things go haywire later on.
You're not passing in the value captured from the NumberToSquare method...
int number=NumberToSquare();
SquareValue(NumberToSquare * NumberToSquare);
NumberToSquare isn't a defined variable so NumberToSquare * NumberToSquare can't calculate, what you'd want is number * number where `number is the value entered by the user.
Your definition of int SquareValue(NumberToSquare, NumberToSquare) expects two parameters although you haven't speified the type. It should be
int SquareValue(int NumberToSquare, int NumberToSquare)
but you have the same variable declared twice which is another error and then you aren't passing two parameters anyway. You want to multiply a number by itself therefore you only have a single source number so why declared two parameters? You need a single parameter method
int SquareValue(int NumberToSquare)
and call like this
int number=NumberToSquare();
SquareValue(number);
Now the SquareValue() method returns an int but you never capture it in the calling code and display the result in the method. Follow the idea in this app that the Main method will do all the orchestration and display, but the SquareValue() method should ONLY do a calculation and not any I/O. I'd also rename the NumberToSquare() method a as what is actually happening ... GetNumberToSquareFromUser().
And there's also a stray " before the closing bracket.
Console.WriteLine("{0} squared is " + result");
And you defined a string output variable which is never used.
And your methods need to be static because main(..) is a static method, not instance. If you declare a Squaring class and instantiated it then you could call non static methods from that.
Also ReadLine() returns a string which can't be assigned to an int.
And finally the result line is implicitly using String.Format behind the scenes but you haven't specified the original number for the {0} token. You could also use interpolation. You could do either of these
Console.WriteLine("{0} squared is " + result, number);
Console.WriteLine($"{number} squared is " + result);
So here's your program revised
class Program
{
static void Main(string[] args)
{
int number = GetNumberToSquareFromUser();
int result = SquareValue(number);
Console.WriteLine("{0} squared is " + result, number);
Console.ReadKey();
}
public static int SquareValue(int numberToSquare)
{
return numberToSquare * numberToSquare;
}
public static int GetNumberToSquareFromUser()
{
Console.WriteLine("Please enter a number to square: ");
int NumberToSquare = int.Parse(Console.ReadLine());
return NumberToSquare;
}
}
I hope this help, I know it's alot to take in, but I hope you take the time to read and really understand rather than just blindly submit the revised version.
When writing your methods, make them reusable. When you start using a method to output to the console in addition to its primary purpose (i.e. to square a number), its re-usability becomes minimal. It is much better to keep specific code in your main method, and put sub tasks into separate methods, such as squaring a number. Now, whenever you need to square a number, you already have a perfectly good method for that.
I didn't handle the case for users entering bad input, but that can be done in the else of the TryParse if block.
static void Main(string[] args)
{
int squredNum = 0;
int NumberToSquare = 0;
Console.WriteLine("Please enter a number to square: ");
if(int.TryParse(Console.ReadLine(), out NumberToSquare))
{
squredNum = SquareValue(NumberToSquare);
Console.WriteLine("{0} squared is {1}", NumberToSquare, squredNum);
}
Console.ReadKey();
}
static int SquareValue(int numberToSquare)
{
return numberToSquare * numberToSquare;
}
p.s. I would not recommend using Math.Pow() to square a number. No need to kill a fly with a bazooka!
Here is an example of such program with robust handling:
using System;
namespace ConsoleApp1
{
internal static class Program
{
private static void Main(string[] args)
{
while (true)
{
Console.WriteLine("Enter value to square or X to exit");
var line = Console.ReadLine();
if (line == null)
continue;
if (line.Trim().Equals("X", StringComparison.InvariantCultureIgnoreCase))
{
Console.WriteLine("Exitting ...");
break;
}
int result;
if (!int.TryParse(line, out result))
continue;
Console.WriteLine(result * result);
}
}
}
}
See the docs online, understand each statement, write your very own program then as your teacher will likely figure out you didn't pull that solely by yourself :)

Passing two arrays from one method to gather user info from another method C#

I'm not looking for specific code, rather, I'm looking for information and guidance. I want to learn but don't really want someone to code it.
I am looking in how to pass two arrays to a different method so they can be filled with user input. I can't seem to figure this out and I have researched various sites as well as my text and lectures and can't find the required techniques to do this. I know how to pass one array to a different method for processing (IE getting avg/sum etcetc) but not how to fill two arrays from one seperate method. Any guidance and information would be greatly appreciated. This is what I've got so far, or rather, what I'm left with. I got the other methods fairly done over, just need this part to move onto the debugging phase.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace PhoneDial
{
class Program
{
// Get player names and their scores and stores them into array for an unknown number of players up to 100
static void InputData(string[] nameList, int[]playerScore)
{
string userInput;
int count = 0;
do
{
Console.Write("\nEnter a players name: ");
userInput = Console.ReadLine();
if (userInput != "Q" && userInput != "q")
{
nameList[0] = Console.ReadLine();
++count;
}
else break;
Console.WriteLine("Enter {0}'s score:", userInput);
playerScore[0] = Convert.ToInt32(Console.ReadLine());
} while (userInput != "Q" && userInput != "q");
}
//Declare variables for number of players and average score and two arrays of size 100 (one for names, one for respective scores
//Calls functions in sequence, passing necessary parameters by reference
//InputData(), passing arrays and number of players variable by reference
//DisplayPlayerData(), passing arrays and number of players by reference
//CalculateAverageScore(), passing arrays and number of players by reference. Store returned value in avg variable
//DisplayBelowAverage(), passing arrays and number of players variable by reference, passing average variable by value
static void Main(string[] args)
{
string[] nameList = new string[100];
int[] playerScore = new int[100];
int count = 0, avg = 0;
InputData(nameList, playerScore);
}
Your question is not entirely clear, but from what I understand, to declare an array in a method and pass to another method to be filled, you just need:
public void MethodA()
{
string[] stringArray = new string[100];
MethodB(stringArray);
}
public void MethodB(string[] stringArray)
{
// Fill the array
stringArray[0] = "Hello";
// ...
}
If, however, you wish to pass some variable reference to a method to then have that method create the array and fill it, you will want to use the ref keyword (as you have with standard variables) on an array variable. Like so:
public void MethodA()
{
string[] stringArray;
MethodB(ref stringArray);
// Array is now created and filled
}
public void MethodB(ref string[] stringArray)
{
// Create the array
stringArray = new string[100];
// Fill the array
stringArray[0] = "Hello";
// ...
}
To do either of these two approaches with two arrays is the same, but with an added parameter. i.e.:
public void MethodB(string[] array1, int[] array2) { }
public void MethodB(ref string[] array1, ref int[] array2) { }
Use Dictionary instead of array.
Dictionary<string, int> Results = new Dictionary<string, int>();
http://msdn.microsoft.com/en-us/library/x525za90%28v=vs.110%29.aspx
You can make the variables nameList and playerScore global by putting them under the class Program{ (dont forget to make the variables static and make lists of them).
then in your InputData use the .add method to add aditional values to the two variables.
Maybe it is also a good idea to use a dictionary instead of two arrays.
I hope this helped

Categories

Resources