I'm working hard on my new project, I'm totally new in C# so I don't really understand much, and I'm making a loading screen now, and do you know that "Loading message".
So I would like to make a few lines, and the code should be able to pick a random line and display when it is loading. Like this example:
var randomLoadingMessage = function() {
var lines = new Array(
"Locating the required gigapixels to render...",
"Spinning up the hamster...",
"Shovelling coal into the server...",
"Programming the flux capacitor"
);
return lines[Math.round(Math.random()*(lines.length-1))];
}
I found it on the internet. How could I use it on c#?
I need help to do something similar in c#
Here are the pieces you need to solve this
A Program. Below is the boilerplate code for a C# console application. Why's this needed? So your line of code has some context to run in. NB: You could run code via LinqPad without this, or you could use a different type of project to host your code; but for now I'm keeping things simple.
using System;
public class Program
{
public static void Main()
{
Console.WriteLine("Hello World");
}
}
An array holding the strings you want to display. See Options for initializing a string array for additional info / options:
string[] lines = new [] {
"Locating the required gigapixels to render...",
"Spinning up the hamster...",
"Shovelling coal into the server...",
"Programming the flux capacitor"
);
A way to pick one of these strings at random. You get a string from the array by putting a number (the index) in square brackets after the variable name, with each item in the array having consecutive numbers starting at 0. ; e.g. lines[1] would give you the string "Spinning up the hamster...". You can get a random number using an instance Random class's Next method. This method requires you to provide parameters to define the range in which the result should fall. The method returns a double but you need an int for your index, so you'll have to convert the result. See How do I generate a random int number in C#? for more.
int randomIndex = myRandom.Next(0, lines.Length);
For now I'll leave it there or I'd be giving you the full solution. If you have issues though, please post new questions here with what you've tried so far, and why it's not working (i.e. are you getting an error message, if so what, or is it doing something different to what you'd expect).
Related
Last night I built my very first interpreter, a BrainFuck interpreter written in C#.
It seemed to work well, until I noticed that it can only take one liners, input such as new lines doesn't get recognized by the program as a suitable input, so it terminates after the first line, as in I paste in 3 lines, it only pastes in the first line and exits with code 0.
I've tried some different approaches such as the Replace() function, but so far no luck, and other related questions' solutions didn't solve it either.
public class Interpreter
{
private byte[] stack;
private int ptr;
private char[] input;
public Interpreter(string input)
{
this.input = input.ToCharArray();
stack = new byte[65535];
}
The issue lies with this.input = input.ToCharArray();.
If I could get some help with figuring out how to fix this bug, I'd really appreciate it. Note that I'm also not a very experienced programmer yet, so feel free to make inputs about anything else as well if you feel the want to.
Here's the source code to the entire project in case it's needed.
https://pastebin.com/eRtHHYDD
Your main method, from your pastebin, is:
var Interpreter = new Interpreter(Console.ReadLine());
Interpreter.Run();
Console.ReadLine() consumes just the first line of input. Your program thus reads the first line, passes it to the interpreter, runs, and then exits without looking at later lines in the standard input stream.
To address this, you'll need to find a way to consume all of the input. Options I can think of, in increasing order of difficulty:
Requiring that the input be specified in a file, not through standard input. You can then use various APIs (e.g. System.IO.File) to read the entire file's text.
Looping over the standard input's lines until none are left, then combining the lines before passing it to your interpreter. If you're expecting the interpreter to take interactive human input, though, this might not be desirable, because ReadLine will block and wait for input if nothing was piped to the process' standard input.
Updating your interpreter so it can take partial input, and pass each line to it as you receive it from standard input.
I am having issues with c# (new to it) but with some programming experience (not great, many moons ago, Python)
I must be doing something wrong and looking for the answer incorrect, spent a couple of days searching for this. I think its really simple and I must be doing something wrong.
Basically I want to take a user input of an interger and store it as an array so I perform maths on individual numbers. However, when I try and get the console to read the number I can not then access the 4th position etc because as c# keeps telling me.
Cannot apply indexing with [] to an expression of type int
what elemental mistake am I making here guys,
Edited to improve original question.
sorry all, that was a little vague. Let me show you how my idea works in python and maybe that would help matters. Basically, i'm trying to access the positions of an integer.
Number = (input("Please enter a Number number"))
check_digit = number[7]
loyalty = number[:-1]
I want the user to enter the number and then the program access different numbers in the array.
Judging from the exception, you probably declare you Array like this:
int myArray;
Instead of this:
int[] myArray;
Error 1 Cannot apply indexing with [] to an expression of type 'int'
I recently came across a php code where a CSV string was split into two variables:
list($this->field_one, $this->field_two) = explode(",", $fields);
I turned this into:
string[] tmp = s_fields.Split(',');
field_one = tmp[0];
field_two = tmp[1];
Is there a C# equivalent without creating a temporary array?
Jon Skeet said the right thing. GC will do the thing, don't you worry.
But if you like the syntax so much (which is pretty considerable), you can use this, I guess.
public static class MyPhpStyleExtension
{
public void SplitInTwo(this string str, char splitBy, out string first, out string second)
{
var tempArray = str.Split(splitBy);
if (tempArray.length != 2) {
throw new NotSoPhpResultAsIExpectedException(tempArray.length);
}
first = tempArray[0];
second = tempArray[1];
}
}
I almost feel guilty by writing this code. Hope this will do the thing.
The answer to your quite narrow question is no. C# does not provide a 'multi-assignment' capability, so you cannot extract an arbitrary set of values from anything (such as Split()) and break them out into individual named variables.
There is a workaround for a specific number of variables, by writing a parameter with out arguments. See #vlad for an answer based on that.
But why would you want to? C# provides an impressive range of features that will allow you to take apart strings and deal them with the parts in a such a wide range of different ways that the lack of 'multi-assignment' should barely be noticed.
Parsing strings usually involves other operations such as dealing with formatting errors, trimming white space, case folding. There could be less than 2 strings, or more. Requirements could change over time. When you are ready for a more capable string parser, C# will be waiting.
You may use the following approach:
-Create a class that inherits from dynamic object.
-Create a local dictionary that will store your variables values in the inherited class.
-Override the TryGetMember and TrySetMember functions to get and set values from and into the dictionary.
-Now, you can split your string and put it in the dictionary, then access your variable like:
dynamicObject.var1
I have a very strange problem that I never been in touch with in my entire life.
This is what I been up to:
I have programmed a game that involves you going to throw two dices and the sum of the two dices should be seven for you to win.
This is how the interface is built:
The textbox1 shows the value of first thrown dice.
The textbox2 shows the value of second thrown dice.
The textbox3 shows the sum of the both dices.
The button1 throws the dices.
This is the problem:
When i Debugg (F5) the application in Visual Studio 2013 Ultimate
the textboxes gets the exactly same value all the time. This is wrong, it shouldn't act like this.
When i Step Into (F11) the application/code the textboxes gets
different values, just as it should be, this is right, this is how the program should act.
Is there anyone that can help with this problem, i think that I have just missed a very small but a obvious thing that I have missed but I really can't find anything, I'm actually out of ideas!
Attachments
Here is all the files, I hope it will help you, the program is written in Swedish but I don't think that makes any problem, if it do, I can translate the whole solution to English.
The whole Solution: Throw_Dices.zip
The Code: Big picture on three screens of the code
From MSDN:
different Random objects that are created in close succession by a
call to the default constructor will have identical default seed
values and, therefore, will produce identical sets of random numbers
In your Kasta.cs, create a static instance of Random instead of multiple ones.
public class Tarning
{
private static Random ran = new Random();
int slump;
public int Kasta()
{
//Random ran = new Random();
slump = ran.Next(1, 6);
return slump;
}
}
Another possibility would be to create a seed manually. For instance like
public int Kasta()
{
byte[] seed = new byte[4];
new RNGCryptoServiceProvider().GetBytes(seed);
int seedInt = BitConverter.ToInt32(seed, 0);
Random ran = new Random(seedInt);
slump = ran.Next(1, 6);
return slump;
}
Instead of creating two Dice (Tarning ?)
Create one and roll it twice.
Or create both on start up, Or perhaps have a class that holds 2 dice.
and throw them again.
You should also google random and seeding, what's happening is from the same seed value, you get the same sequence of random numbers. Debugging is introducing enough of a delay between the new Random calls, that the seed (based on the clock) has changed between the two calls.
PS your button1Click handler
should set the three textbox values, not trigger textbox changed events which then set them. Imagine if you wanted to reuse your code, you'd have to create a UI to do it.
A better way would be to have a class that held two (or n) dice with a Roll method and a property that returned the result. Then you could reuse it without worrying about when and how.
I have a folder ~/ConfigurationDirectory. The sub-folders within this folder are named as follows
5.0.0.1
5.0.0.2
5.0.0.3
...
Now, the requirement is that - Identify the folder which has the "largest" name numerically and create a copy of the folder. Rename the new folder as 5.0.0.n+1 (assuming that the largest numerically available folder is 5.0.0.n)
I have written code which will identify the largest named folder. Also, I have written the code which will do the copy of folder and sub-folders. What I am not able to get is, how do I get the name of the new folder, i.e., 5.0.0.n+1
How do I do this in C#? Any pointers would suffice rather than complete coding.
Thanks!
Assuming the numbers you're working with are not simple four-part version numbers, you're going to want to use the string.Split() to break up the folder name, and then Convert.ToInt32() or int.Parse() to turn the last chunk into a number. From there, you increment it, and then use something like string.Format() to turn it back into a folder name.
If, however, you are indeed working with simple version numbers, then using the System.Version class (specifically, the Parse() or TryParse() and ToString() methods) would be a significantly more straightforward implementation.
This is the most correct solution, imo:
Version version;
if (Version.TryParse("5.0.0.0", out version))
{
// your logic here
return new Version(
version.Major,
version.Minor,
version.Build,
version.Revision + 1).ToString();
// will return 5.0.0.1
}
else
{
// error handling here
}
You can use string.LastIndexOf for this purpose (this is much more light-weight than using string.Split):
static string GetNextFolderName(string folderName)
{
int lastDotPosition = folderName.LastIndexOf('.');
string lastPartOfFolderName = folderName.Substring(lastDotPosition + 1);
int number;
if (int.TryParse(lastPartOfFolderName, out number))
{
number++;
return folderName.Substring(0, lastDotPosition + 1) + number.ToString();
}
else
{
// You've got a problem on your hands, here.
throw new FormatException();
}
}
UPDATE: It has been pointed out that this approach is perhaps excessive in light of the existence of Version.TryParse. A few points in response to that:
Version.TryParse is available as of .NET 4.0. Many developers are not using .NET 4.0; therefore to discard any alternative approach right out is (in my opinion) quite narrow-sighted.
It has not been indicated whether performance is much of a concern. Presumably, it is not. However, when you think about the problem conceptually, Version.TryParse is actually doing significantly more work than we need in this case: it is looking at every individual component of the version string and parsing them all into a complete Version object. The approach outlined above, on the other hand, only bothers to examine the last part of the version string, and is therefore more efficient. I have verified this: using the approach above executes in about 30% of the time it takes using Version.TryParse.
Of course it is fair to point out that, if one already knew of Version.TryParse and chose to write the above code anyway, one would be guilty of premature optimization. That said, suppose you did not know about it, and you already wrote the above code. Would the right thing to do be to refactor the code to use Version.TryParse, keeping the same functionality and slowing performance by about 200%? I'm not asking rhetorically; perhaps in some cases, for the sake of simplicity and maintainability, it might be. But it would be a judgment call.
I post these points primarily as a rebuttal to anyone who would immediately dismiss a solution simply because it performs the same task as an "out-of-the-box" solution. Sometimes, depending on your circumstances, it can make sense to do something yourself anyway. Just know what you're getting yourself into, and be ready to take a step back and change direction if and when it becomes appropriate to do so.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections;
namespace ConsoleApplication1
{
static class Extensions
{
public static TOutput[] ToArray<TSource, TOutput>(this IEnumerable<TSource> col, Converter<TSource, TOutput> converter)
{
return Array.ConvertAll<TSource, TOutput>(col.ToArray(), converter);
}
}
class Program
{
static void Main(string[] args)
{
string original = "5.0.0.0";
int[] tmp = original.Split('.').ToArray<string, int>(new Converter<string, int>(delegate(string s)
{
int result;
return int.TryParse(s, out result) ? result : 0;
}));
tmp[tmp.Length - 1]++;
// re should contain 5.0.0.1
string re = String.Join(".", tmp);
}
}
}
It's a simple algorithm, which can be applied to any number of elements:
Split the string on the dots. Call the resulting array a.
Convert the last element of a to an integer. Call this integer i.
i++
a[last] = i.ToString()
Join the elements of a using a dot as the separator.
Make sure that your identification algorithm really does select the numerically largest value: if you have 5.0.0.9 and 5.0.0.10, then you would find 5.0.0.9 if the identification really uses alphabetic ordering.