compiler is printing Strange value in c# [duplicate] - c#

This question already has answers here:
printing all contents of array in C#
(13 answers)
How does the .ToString() method work?
(4 answers)
Closed 6 years ago.
I am using methods in c#. i returned something but compiler is not printing which i am expecting. It is printing (system.string[]). i dont know why Please help on this.
class Program
{
static void Main(string[] args)
{
string[] sub = subjects();
Console.WriteLine(sub);
}
public static string[] subjects()
{
Console.WriteLine("Please Enter How many Subject Do you Want to input");
int limit = System.Convert.ToInt32(Console.ReadLine());
string[] Subjects = new string[limit];
for (int i = 0; i < limit; i++)
{
Console.WriteLine("Please Enter Subject Name " + i);
Subjects[i] = Console.ReadLine();
}
return Subjects;
}
}

The reason that Program is printing system.string[] is because class string[] does not override ToString method, so the default one is used and the default ToString returns type name, not the "value" inside type.
You can use for example String.Join method to build one string from array of strings and put given delimiter between each string:
Console.WriteLine(String.Join(", ", sub));

Console.WriteLine(sub)
wont show you anything of value (it prints the sub type), since you are not referencing any value of the sub array, e.g sub[0]. Try this:
foreach (string s in sub)
{
Console.WriteLine(s);
}

Console.WriteLine(String.Join(", ", sub));

Related

How do I make permanent changes to a variable within for loops so that the variable doesn't reset every iteration? [duplicate]

This question already has answers here:
string.Replace (or other string modification) not working
(4 answers)
Closed 3 years ago.
I want to replace characters in a string iteratively using the string.Replace() function in a for loop however every iteration the string itself resets and no changes made in the previous loop stay. Ending up in the string undergoing no changes overall.
I've tried making the string a class member but that didn't work,
static void Main(string[] args)
{
int i;
string strOne = "abcdefg";
for (i=0; i < (strOne.Length - 1); i++)
{
string c = Convert.ToString(strOne[i]);
strOne.Replace(c, "1");
}
}
I expect the output of 1111111 but instead i get abcdefg.
When you call string.Replace(), it does not modify the string itself. Instead, it returns the string with the replaced characters. Therefore, you need to do this: strOne = strOne.Replace(c, "1");

check ALL arguments in c# that they can be numeric [duplicate]

This question already has answers here:
Identify if a string is a number
(26 answers)
Closed 6 years ago.
I am writing a small console application in C# and it requires two numeric parameters/arguments to be passed to it. I am checking for no params, more than 2 params, if two params. I am also converting those params if 2 returned to numeric for calculations I'm doing. One thing I'm not doing is verifying what's being passed is a number so assume program will crap out if I pass a letter. Is there a look routing I can just run to verify the params passed are in deed able to be numbers? I can handle the kick out from there but curious how you check if an argument CAN be a number or not.
Thanks.
JR
I would simplify this task as follows:
Create custom Convert method:
static double Convert(string s)
{
double result;
if (!double.TryParse(s, out result))
result = double.NaN;
return result;
}
Use it in Main:
static void Main(string[] args)
{
var doubles = args.Select(a => Convert(a)).ToArray();
var valid = doubles.All(a => !double.IsNaN(a));
}
Here's one way;
static void Main(string[] args)
{
foreach (var arg in args)
{
int asInt;
// Returns "true" if arg can be parsed as an int and false otherwise;
// If you want to allow doubles you can also try double.TryParse in a similar manner
if (int.TryParse(arg, out asInt))
{
// Handle
}
// Failed to parse argument as an int
else
{
throw new ArgumentException("arg not an int");
}
}
}
You could also use a Regex:
static void Main(string[] args)
{
// Make sure this can is either an int or a double
var regex = new Regex(#"^-?(([0-9]+)|([0-9]+\.[0-9]+(e[0-9]+)?))$");
foreach (var arg in args)
{
if (!regex.IsMatch(arg))
throw new ArgumentException("arg " + arg + " is not an int or double");
}
}
Note a few important features of this regex:
- The "#" literal symbol in front of the regex string
- The ^ and $ to mark the beginning and end of lines - i.e. the string must contain only a number or only a double
- This bans empty strings as well
Edit: I edited the Regex to optionally allow for something like "1.0e100" or "-123", which, as pointed out in the comments, are also perfectly valid ints and doubles. Also, as pointed out in the comments, it's probably better to use int.TryParse or double.TryParse rather than reinventing the wheel.
There's also Char.IsDigit which always feels cleaner to me than checking for a failed parsing attempt. If you care about micro-optimizing, char.IsDigit is probably faster than parsing an invalid string too.
Or, if negative numbers or non-whole numbers are your thing, you can use char.IsNumber
See: https://msdn.microsoft.com/en-us/library/7f0ddtxh(v=vs.110).aspx
public static void Main(string[] args)
{
for(int i = 0; i < args.Length; i++)
{
if(args[i].All((c) => char.IsDigit(c))
{
//It's a number.
}
}
}

Why am I printing out 'System.Int32[]' instead of my array of numbers? [duplicate]

This question already has answers here:
C# multidimensional arrays iteration
(5 answers)
Closed 2 years ago.
I am trying to print out my array of numbers that I have assigned to a particular array. My algorithm for choosing numbers consists of choosing a random number that is not a duplicate and storing it inside the array.
Pretty simple really, but I have no idea as to why it is printing out this error.
int[] ticket1 = new int[4];
for (int i = 0; i < 4; i++)
{
int temp = rand.Next(43);
while (ticket1.Contains(temp))
{
temp = rand.Next(43);
}
ticket1[i] = temp;
}
Console.WriteLine("{0}{1}", item.PadRight(20), ticket1.ToString());//ticket1 produces System.Int32[] instead of 4 numbers.
//I have changed this line to:
//Console.WriteLine("{0}{1}", item.PadRight(20), string.Join(",", ticket1));
//And it still doesn't work. the error remains. (System.Int32[])
My question is, how can I print out my 4 numbers (beside each other) in string format.
//EDIT: I've found my problem. I am putting my ticket1 inside a foreach loop, it's somehow not reaching out to the array values and it therefore prints out System.Int32[] instead.
All fixed.
If you call ToString() on an array like that, you simply get the full name of the type of class.
You could fix it a few ways. Print only the current item inside the loop, or print each item one at a time outside of the loop:
Console.WriteLine("{0}{1}", item.PadRight(20), ticket1[0]);
Console.WriteLine("{0}{1}", item.PadRight(20), ticket1[1]);
// etc...
Or "flatten" the collection before printing:
Console.WriteLine("My numbers: ", String.Join(", ", ticket1));
ticket1.ToString() does not print the content of the array, only its type, because this is the way the ToString() method is implemented on arrays.
You can fix this in several ways - for example, by using string.Join method:
Console.WriteLine("{0}{1}", item.PadRight(20), string.Join(",", ticket1));
Because you are not writing your array elements, you are writing your array itself, that's why ToString() generates it's full type name.
Change your ticket1.ToString() to ticket1[i] in your for loop.
for (int i = 0; i < 4; i++)
{
int temp = rand.Next(43);
while (ticket1.Contains(temp))
{
temp = rand.Next(43);
}
ticket1[i] = temp;
Console.WriteLine("{0} {1}", item.PadRight(20), ticket1[i]);
}
If you don't want to print it inside your for loop, then you can use String.Join to concatenate all your elements in your array in a simple string like;
for (int i = 0; i < 4; i++)
{
int temp = rand.Next(43);
while (ticket1.Contains(temp))
{
temp = rand.Next(43);
}
ticket1[i] = temp;
}
Console.WriteLine("{0} {1}", item.PadRight(20), string.Join(",", ticket1));
Because when you call .ToString() on an object you get the type of that object. For basic primitive (value) types this behavior is overridden to output the value. But for something like an array there's no "default" string representation, so the behavior you're seeing is the default.
You could wrap your data in an object and override .ToString() on that object. If you have to output the values in many places in the code that would be the way to go so you only have to write the logic once. ("Smart data structures and dumb code works a lot better than the other way around." - Eric Raymond)
But if you only need to do it here then you can just output the values directly. Basically join the values as a string in whatever representation you want. For example, if they should be comma-separated:
Console.WriteLine(
"{0}{1}",
item.PadRight(20),
string.Join(",", ticket1));

Array.ToString() returning System.Char[] c#

Im making a hangman game, at the start of the game the word that the player must guess is printed as stars. I have just started making it again after attempting to write it once and just having messy code that i couldn't bug fix. So I decided it best to write it again. The only problem is, when i try to get my array to print out by using array.ToString(); it just returns System.char[]. See below.
code:
class Program
{
static void Main(string[] args)
{
string PlayerOneWord;
string PlayerTwoGuess;
int lives = 5;
Console.WriteLine("Welcome to hangman!\n PLayer one, Please enter the word which player Two needs to guess!");
PlayerOneWord = Console.ReadLine().ToLower();
var stars = new char[PlayerOneWord.Length];
for (int i = 0; i < stars.Length ; i++)
{
stars[i] = '*';
}
string StarString = stars.ToString();
Console.Write("Word to Guess: {0}" , StarString);
Console.ReadLine();
}
}
output:
The output should say Word to guess: Hello.
Please will someone explain why this is happening as its not the first time I have run into this problem.
Calling ToString on a simple array only returns "T[]" regardless what the type T is. It doesn't have any special handling for char[].
To convert a char[] to string you can use:
string s = new string(charArray);
But for your concrete problem there is an even simpler solution:
string stars = new string('*', PlayerOneWord.Length);
The constructor public String(char c, int count) repeats c count times.
The variable stars is an array of chars. This is the reason you get this error. As it is stated in MSDN
Returns a string that represents the current object.
In order you get a string from the characters in this array, you could use this:
Console.Write("Word to Guess: {0}" , new String(stars));
The correct way to do this would be:
string StarString = new string(stars);
ToString() calls the standard implementation of the Array-class's ToString-method which is the same for all Arrays and similarily to object only returns the fully qualified class name.
Try this code:
static string ConvertCharArr2Str(char[] chs)
{
var s = "";
foreach (var c in chs)
{
s += c;
}
return s;
}

How to create one string from list of String? [duplicate]

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
Concat all strings inside a List<string> using LINQ
I am using C# 4.0, where I have a list non-null of string objects.
IList<String> Errors
What I want to do is to create a single string which has all list elements appended, one after another, with a new line character.
public String ErrorMessage
{
get { return Errors.SomeMethodHere(); }
}
One way I could think of is to loop on list of string. Is there any better way or in built System.String or LINQ method which I can use for this?
String.Join(Environment.NewLine, Errors.ToArray());
Try String.Join(Environment.NewLine, Errors.ToArray()) (for .NET 4 and up you don't need the ToArray)
More Info: http://msdn.microsoft.com/en-us/library/57a79xd0.aspx
public String ErrorMessage
{
get
{
//Use your appropriate separator instead of ','
return string.Join(",", Errors);
//return string.Join("", Errors); // Just concatenating all message
}
}
Errors.Aggregate((left, right) => string.Format(#"{0}\n{1}", left, right));
public static class MyExtensions
{
public static string ErrorMessage(this IList<String> strList)
{
string retMessage = null;
for (int i = 0; i < strList.Count; i++)
{
retMessage += strList[i].ToString() + Environment.NewLine;
}
return retMessage;
}
}
you can use the above code snippest to make an extended method to generate single string from list data.

Categories

Resources