How do I arrange the numbers next to each other instead of on top of each other?
I tried implementing \t but it gives me an error or doesn't do anything at all.
int[] anzFeldElemente = new int[10];
Random wuerfel = new Random();
for (int i = 0; i < anzFeldElemente.Length; i++)
{
anzFeldElemente[i] = wuerfel.Next(0, 100);
}
Array.Sort(anzFeldElemente);
foreach (int i in anzFeldElemente)
{
Console.WriteLine(i "\t");
}
Console.ReadLine();
Also, is it possible to draw a field similar to Microsoft Excel in a console app? Is there a function to draw one?
Thanks in advance.
Using Console.WriteLine will force it to move to the next line every time you iterate. As recommended by lazyberezovsky use the Console.Write instead. Remember to include a white space to divide up the elements using +", "
As the name implies, Console.WriteLine writes a line.
Instead of
Console.WriteLine(i "\t");
Try
Console.Write(i + "\t");
Or
Console.Write("{0}\t", i);
It should be like this:
Console.Write(i + "\t");
Related
My apologies if I didn't explain it clear the first time. I have edited my explanation further in bold below.
In the program below user enters a word and then enters a letter which the user would like to replace with any character. For instance, user enter's a word "Hello" and the replacement letter is "l" with "$". So "Hello" will become "He$$o". First, the goal is to find the location of "l" (example - 2,3) and then replace the element in that specific location.
I started by finding the location of "l" and storing it in a findIndex array. Every time I run the program I get "22222" stored in findIndex[] array. At this point, I am not even sure if I am even applying the right logic. Any advice will be appreciated! Please don't use LINQ.
public static void RemoveSpecifiedCharacters()
{
Console.WriteLine("\nWrite a word/sentence: ");
string myString = Console.ReadLine();
Console.Write("Type the character you would like to replace: ");
string myCharacter = Console.ReadLine();
int[] findIndex = new int[myString.Length];
for (int i = 0; i < myString.Length; i++)
{
findIndex[i] = myString.IndexOf(myCharacter, 0);
}
for (int i = 0; i < findIndex.Length; i++)
{
Console.Write(findIndex[i]);
}
}
This is probably what you want :
public static void RemoveSpecifiedCharacters()
{
Console.WriteLine("\nWrite a word/sentence: ");
string myString = Console.ReadLine();
Console.Write("Type the character you would like to replace: ");
string myCharacter = Console.ReadLine();
List<int> findIndex = new List<int>();
int offs = 0;
while (offs < myString.Length)
{
offs = myString.IndexOf(myCharacter, offs);;
if (offs == -1)
break;
findIndex.Add(offs);
offs++;
}
for (int i = 0; i < findIndex.Count; i++)
{
Console.Write(findIndex[i]);
}
}
Set an initial offset to the start of the string, try to find index of required character if not found exit, otherwise store the location & increment the offset so the next loop starts after the found position. Then keep looping.
As you do not know how many characters will be found, then a list is better than an array to store the results. It can always be converted to an array with .ToArray() afterwards.
Below should serve the purpose :
var str = "Hello";
var replaced = str.Replace('l', '$');
Even though it's easier to use String.Replace, I just want to give you an explanation why you are getting [2,2,2,2,2] array.
Firstly, IndexOf method returns index of character's first occurence, starting from 0.
Secondly, you are using method overload IndexOf(myCharacter, 0) which "says" that character search should be done always from the start of the string.
To circumvent the issue, you should use IndexOf(myCharacter, i, 1) instead to set the search to start from i-th character, not the start of string.
I guess a simple solution would be to split the string into a character array and then do the comparison?
For example something like:
Console.WriteLine("\nWrite a word/sentence: ");
char[] myString = Console.ReadLine().ToCharArray();
Console.Write("Type the character you would like to replace: ");
char myCharacter = Console.ReadLine().ToCharArray()[0];
int[] findIndex = new int[myString.Length];
int indexCount = 0;
for (int i = 0; i < myString.Length; i++)
{
if (myString[i] == myCharacter)
findIndex[indexCount++] = i;
}
for (int i = 0; i < indexCount; i++)
{
Console.Write(findIndex[i]);
}
for (int i = 0; i < richTextBox2.Lines.Length; i++)
{
richTextBox2.Lines[i] = richTextBox2.Lines[i].Insert(0, i + " ");
}
Before that tried with the Insert:
richTextBox2.Lines[i].Insert(0, i + " ");
In both cases it's not adding any numbers.
For example if the lines are:
Hello world
Hi
Hello
Then i want it to be now:
1 Hello world
2 Hi
3 Hello
But the loop does nothing it's not adding any numbers.
You can't modifiy the single line in that way. If you look at MSDN you will find this remark
By default, the collection of lines is a read-only copy of the lines
in the TextBox. To get a writable collection of lines, use code
similar to the following: textBox1.Lines = new string[] { "abcd" };
So the correct way to reach you goal is
string[] lines = richTextBox2.Lines;
for (int i = 0; i < lines.Length; i++)
{
lines[i] = (i+1) + " " + lines[i];
}
richTextBox2.Lines = lines;
You can try using Linq:
using System.Linq;
...
richTextBox2.Lines = richTextBox2
.Lines
.Select((line, index) => $"{index + 1} {line}")
.ToArray();
please, avoid redrawing UI (esp. RichTextBox) which can slow down your application, but build the data (lines, text) and then assign it in one go.
My question is how to output things in the array in reverse order
grouped by two things with resorting only to the while-loop
(i.e., without for-loop and Reverse method, etc.)
I know that the second while-loop is not correct but I do not know how to modify it.
Thank you in advance for your suggestions.
Console.WriteLine("Please type four things.");
const int MAX_SIZE = 4;
string[] things = new string[MAX_SIZE];
int i = 0;
while (i < MAX_SIZE)
{
Console.WriteLine("Please type the things.");
things[i] = Console.ReadLine();
i++;
}
i = 0;
while (i < MAX_SIZE)
{
Console.Write(things[i] + ", ");
i--;
}
Try
i = MAX_SIZE - 1
while (i >= 0)
{
Console.Write(things[i] + ", ");
i--;
}
The reason I am using MAX_SIZE-1 is because arrays in C# are 0-based. The first element will always be in position 0. If the array has 4 elements, the final element will be in position 3.
If you want to print things in twos, you can just do the following:
i = MAX_SIZE - 1
while (i >= 0)
{
Console.Write(things[i-1] + ", " things[i]);
i -= 2;
}
Is there any reason you want to use a while loop instead of a for loop?
for(var i=0;i<MAX_SIZE;i++) {
Console.WriteLine("Please type the things.");
things[i] = Console.ReadLine();
i++;
}
for(var i=MAX_SIZE-1;i>=0;i--){
Console.Write(things[i] + ", ");
}
If I understand the task correctly, next code should work for you:
int i = things.Length - 1;
while(i > 0)
{
Console.Write("({0}, {1}) ", things[i], things[i - 1]);
i -= 2;
}
//in case the the list lenght is odd, output the last element without pair
if(i == 0)
{
Console.Write("({0})", things[i]);
}
if statement can be omitted if things list length is always even because it is required only if you need to pring the last (the first in things list) element, which has no pair.
I'm new to C# and programming as a whole and i have a quick question to ask you guys, I've searched a bit but only found far too complicated examples for me to implement in my work so here goes:
int[] newArray = new int[7];
Console.WriteLine("Hello! Please enter 7 numbers between 1-25, press ENTER after each number. ");
for (int i = 0; i < newArray.Length; i++)
bool loop = true;
do
{
try
{
newArray[i] = Convert.ToInt32(Console.ReadLine());
loop = false;
}
catch
{
Console.WriteLine("You may only enter numbers!");
}
} while (loop);
Console.Write("You entered the following numbers: ");
for (int i = 0; i < newArray.Length; i++)
{
Console.WriteLine(newArray[i]);
}
}
This is the first part of a bingogame im trying to write, but i can't understand why the names loop and i don't exist, should i make something static? Move some brackets around? Please help.
You need to wrap the entire for statement in braces, otherwise it will only execute the next line of code, which is just bool loop = true;.
for (int i = 0; i < newArray.Length; i++)
{ // <-- Add this
bool loop = true;
do
{
try
{
newArray[i] = Convert.ToInt32(Console.ReadLine());
loop = false;
}
catch
{
Console.WriteLine("You may only enter numbers!");
}
} while (loop);
Console.Write("You entered the following numbers: ");
}
It's worth to mention about string.Join method to print all elements of the list.
Console.WriteLine("You entered the following numbers: ");
Console.WriteLine(string.Join(", ", newArray));
After using Parse/TryParse method, you don't need to use Convert.ToInt32 any more.
To validate number and be able to reenter it, it is much better to do 2 IF statements instead of using Constains method of Enumerable class.
while (!int.TryParse(Console.ReadLine(), out number) || number < 1 || number > 25)
{
Console.WriteLine("You may only enter numbers from range 1-25!");
}
Make one single bracket right after your for cycle.
You're missing an open brace. This looks like homework so I'm not going to rewrite it for you. Take a closer look and work on the formatting and indentations. That will give you a clue as to were that missing brace should be.
Here is a nicer way to test for number input without the try/catch
var newArray = new int[7];
Console.WriteLine("Hello! Please enter 7 numbers between 1-25, press ENTER after each number. ");
for (var i = 0; i <= newArray.Length - 1; i++)
{
int number;
while (!int.TryParse(Console.ReadLine(), out number))
{
Console.WriteLine("You may only enter numbers!");
}
newArray[i] = Convert.ToInt32(number);
}
Console.WriteLine("You entered the following numbers: ");
foreach (var t in newArray)
{
Console.WriteLine(t);
}
int LetterCount = 0;
string strText = "Debugging";
string letter;
for (int i = 0; i <strText.Length; i++)
{
letter = strText.Substring(0, 9);
if(letter == "g")
{
LetterCount++;
textBox1.Text = "g appears " + LetterCount + " times";
}
}
So, I'm doing this tutorial thing, and I've been stuck on this exercise for like 4 hours. And I can't figure out what's wrong with my For Loop.
The point of the exercise is to make my program thing tell me how many g's are in the word debugging. But you probably figured that out. Anyway, I'm not even sure that I have the right code for telling me that, because I think that I need to change the second part of the For Loop (the i < ) part.
But my problem is that it isn't registering the "if letter == "g" " at all. Because according to my locals window it says that letter=Debugging, which would make me think that g should be registering on my program 24 times, I think (because str.length is 9 letters long?) But it's registering as 0 no matter what I do.
You are extracting a string of 9 characters. It will never be equal to "g" (which only has one). Here's how I'd do it.
int count = 0;
foreach (char c in strText)
{
if (c == 'g')
count++;
}
Using the for loop:
for (int i = 0; i < strText.Length; i++)
{
if (strText[i] == 'g')
count++;
}
Take a look at the documentation for string.Substring(x, y).
Basically:
letter = strText.Substring(0, 9);
Isn't giving you a letter. Each time through it's giving you all 9 characters of the string strText. You might want to consider using the variable i for one of the values you pass to Substring.
(I've deliberately not given you the entire answer as you seem to want to understand, so, if the pointers I've given don't get you there, let me know and I'll expand my answer =)
Try this:
for (int i = 0; i <strText.Length; i++)
{
if(strText[i] == 'g')
{
LetterCount++;
}
}
textBox1.Text = "g appears " + LetterCount + " times";
The issue is that you are looking at the entire string when you compare to "g". By specifying an index you are telling it to look at a specific character in the string. Also, I removed your substring because it did not appear to be doing anything.
You're not using i at all in your for loop.
Do you mean
letter = strText.Substring(i, 1);
?
Well, you are taking substring that is long 9 charachters and comparing it to "g". It won't be equal.
You should try:
letter = strText.Substring(i,1);
Because String.Substring(int, int) takes two arguments: the offset and amount to take.
In your case, letter = strText.Substring(0, 9); will simply assign letter's value to "Debugging". If you want to check each letter individually, you need to write letter = strText.Substring(i, 1).
You're probably looking for something like this:
int LetterCount = 0;
string strText = "Debugging";
string letter;
for (int i = 0; i <strText.Length; i++)
{
letter = strText.Substring(i, 1);
if(letter == "g")
{
LetterCount++;
textBox1.Text = "g appears " + LetterCount + " times";
}
}
letter = strText.Substring(0, 9);
at this point, 'letter' has the value "Debugging" since you're taking the entire string.
Try letter = strText[i] so you isolate the single letter.
What #Rob said.
Try something like this:
int gCount = 0;
string s = "Debugging";
for ( int i = 0; i <strText.Length; i++)
{
if ( s[i] == 'g' ) ++gCount ;
}
textBox1.Text = "g appears " + gCount+ " times";
namespace runtime
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
int lettercount = 0;
string strText = "Debugging";
string letter;
for (int i = 0; i < strText.Length; i++)
{
letter = strText.Substring(i,1);
if (letter == "g")
{
lettercount++;
}
}
textBox1.Text = "g appear " + lettercount + " times";
}
}
}