C# method lines program - c#

I need method of lines, so that when you have method call Rows (4), a method prints four blank lines.
This is my code but it wont work, tell me what is wrong?
namespace something
{
class Program
{
static void Main(string[] args)
{
Console.Write("give number: ");
int lines = int.Parse(Console.ReadLine());
line(lines);
Console.WriteLine("lines end");
Console.ReadKey();
}
private static void line(int lines)
{
for (int i = 1; i <= lines; i++);
Console.WriteLine(" ");
}
}
}

Remove ; at the end:
for (int i = 1; i <= lines; i++);
^
In this case your Console.WriteLine(" "); called only once after loop finished. Loop doing nothing.

for (int i = 1; i <= lines; i++); // note the semicolon!
Console.WriteLine(" ");
Should be
for (int i = 1; i <= lines; i++)
Console.WriteLine(" ");
The colon is an empty instruction in its own right. So basically your program was executing an empty instruction n times (or 'lines' times, actually), and it would write an empty line only ever once afterwards.
Interestingly, the Possible mistaken empty statement compiler warning is only displayed when you enwrap the Console.WriteLine line in brackets.
Whatever causes that, it seems like a one more good reason to use brackets, even for code blocks consisting of single instructions.
Thus I would recommend:
for (int i = 1; i <= lines; i++)
{
Console.WriteLine(" ");
}

The semi-colon on the end of your for clause is the issue. Your loop isn't doing anything.
for (int i = 1; i <= lines; i++)
Console.WriteLine(" ");

First of all you should check for the user input to be a number, and display an error message if it isn't. The code, like that, will throw an exception if the user inputs something that can't be parsed to an int.
Then there's the semicolon at the end of the for. That's a compiler error which I think you already noticed when trying to run it.
Apart from that, what exactly is not working? Your "line" method is printi a white space for every number, and not a line. If you want to print a blank line, use Environment.NewLine

Related

Is there such a thing as an array without size?

I am playing with C#. I try to write program that frames the quote entered by a user in a square of chars. So, the problem is... a user needs to indicate the number of lines before entering a quote. I want to remove this moment, so the user just enters lines of their phrase (each line is a new element in the string array, so I guess a program should kinda declare it by itself?..). I hope I explained clear what I meant x).
I've attached the program code below. I know that it is not perfect (for example, when entering the number of lines, I use the conversion to an integer, and if a user enters a letter, then this may confuse my electronic friend, this is a temporary solution, since I do not want to ask this x) The program itself must count these lines! x)) Though, I don't understand why the symbols on the left side are displayed incorrectly when the program displays output, but I think this also does not matter yet).
//Greet a user, asking for the number of lines.
Console.WriteLine("Greetings! I can put any phrase into beautiful #-square."
+ "\n" + "Wanna try? How many lines in the quote: ");
int numberOfLines = Convert.ToInt32(Console.ReadLine());
//Asking for each line.
string[] lines = new string[numberOfLines];
for (int i = 0; i < numberOfLines; i++)
{
Console.WriteLine("Enter the line: ");
lines[i] = Console.ReadLine();
}
//Looking for the biggest line
int length = 0;
for (int i = 0; i < numberOfLines; i++)
{
if (length < lines[i].Length) length = lines[i].Length;
}
//Starting framing
char doggy = '#';
char space = ' ';
length += 4;
string frame = new String(doggy, length);
Console.WriteLine(frame);
for (int i = 0; i < numberOfLines; i++)
{
string result = new string(space, length - 3 - lines[i].Length);
Console.WriteLine(doggy + space + lines[i] + result + doggy);
}
Console.WriteLine(frame);
Console.ReadLine();
}
}
}
There is performance gap and functionality between "Generic Lists" and arrays, you can read more about cons and pros of this two objects in the internet,
for example you can use list as Dai mentioned in comment like this
List<string> list = new List<string>();
list.Add("one");
list.Add("two");
list.Add("three");
or you can use arraylist
ArrayList arraylist = new ArrayList();
arraylist.Add();
or even you can change the size of array any times but it erase data in it
int[] arr = new int[100];
there is a function called ToArray() you can use it to change generic list to array
Your problem of the left side output is, that you add two values of char. This is not what you expect to be. You must convert the char to a string to append it to other strings:
Console.WriteLine(doggy.ToString() + space.ToString() + lines[i] + result + doggy.ToString());

Print ASCII of a triangle shape with variable input

Struggling with the print. I know it should be two for loops to print out the repeated letters, however, having problems to indent the lines. it should be a simple console C# program to print out the shape like below with a input 3.
XXXXX
XXX
X
With input 4 it should be like
XXXXXXX
XXXXX
XXX
X
Here is my code. Two for loops get the letters correctly but the lines all lined up at the left, not center.
static void Main(string[] args)
{
string num = Console.ReadLine().Trim();
int n = Convert.ToInt32(num);
int k=1;
for(int i = n; i>=1; i--)
{
Console.WriteLine("\n");
Console.WriteLine("".PadLeft(n));
for (int j = (2*i-1); j>=1;j--)
{
Console.Write("0");
}
}
Console.Read();
}
The statement:
Console.WriteLine("".PadLeft(n));
is the right idea but it's not quite there.
In your case, n is the number of lines you wish to print and is invariant. The number of spaces you need at the start of each line should begin at zero and increase by one for each line.
In any case, printing any number of spaces followed by newline (because it's WriteLine) is not what you want, you should be using Write instead.
So the code between int n = Convert.ToInt32(num); and Console.Read(); would be better off as something like:
for (int lineNum = 0; lineNum < n; lineNum++) {
int spaceCount = lineNum;
int xCount = (n - lineNum) * 2 - 1;
Console.Write("".PadLeft(spaceCount));
Console.WriteLine("".PadLeft(xCount, 'X'));
}
You'll notice some other changes there. First, I've used more meaningful variable names, something I'm a bit of a stickler for - using i is okay in certain circumstances but I often find it's more readable to use descriptive names.
I've also used PadLeft to do the X string as well, so as to remove the need for an inner loop.

Index variable breaking? Looping in C#, Visual Studio 2015

today I have an issue which is driving me up a wall. I am a novice programmer, currently learning the basics of C#, after learning Java.
Today, I was working on a practice example when I encountered this problem:
Code Running
This is a screenshot of my code running, and I have left a print statement inside the loop to show me what my index variable is doing. As you can see, it is incrementing more than once per each execution of the loop. I have also gotten the same results when using a while loop, and in other projects.
Here is the code:
class Program
{
static void Main(string[] args)
{
Console.WriteLine("How many values are you entering");
int value = Convert.ToInt32(Console.Read());
Console.WriteLine("Please enter the values of the currencies you are converting.");
decimal[] money = new decimal[value];
for (int i = 0; i < money.Length; i++)
{
money[i] = Convert.ToDecimal(Console.Read());
Console.WriteLine("i is: "+i);
}
}
}
I cannot really proceed with this assignment until I can figure out what is causing this issue. Thanks!
try ReadLine() instead of Read() like
Console.WriteLine("How many values are you entering");
string input = Console.ReadLine();
int value = Convert.ToInt32(input);
Console.WriteLine(value +" Please enter the values of the currencies you are converting.");
decimal[] money = new decimal[value];
for (int i = 0; i < money.Length; i++)
{
money[i] = Convert.ToDecimal(Console.ReadLine());
Console.WriteLine("i is: " + i);
}
Hi Welcome to the wonderful world of C#
Your problem here is Console.Read()
Console.Read() will give you an int of the character 4 which is your first typed character. And that character will be 52.
So it will loop 52 times.
Instead of Console.Read() use Console.ReadLine()

Use Substring method to count specific character from a string

So I am new to programming and one of my exercises involves using a substring within a loop to count the number of iterations of a specific character with a user's input.
As far as I can tell for the exercise, and what I know in C sharp so far, using a substring in this will only help read the position of a character within the input, and will not count it. I can not make heads or tails of this, and am at a loss.
I want to know how to understand this, and what ways I am missing the point of the exercise.
I need an idea of how to set the substring to read the number of a certain character type from the end-user's input from console.
This is the original question:
There is a method called Substring that we can use with a string to look at a portion of a string.
For example, the following code will print the letter a.
string input = "abcdef";
Console.WriteLine(input.Substring(0, 1));
Assignment:
Given the following input, create a loop that uses the Substring method to count the number of times the letter ā€˜zā€™ occurs in a string input by the user.
asdfojiaqweb;ounqwrb;ounwqen;zzzn bnaozonza
Edit: So Far I have the code to count the number of times that Z is used, but I don't know how to incorporate a substring into it
int total = 0;
var letter = new HashSet<char> { 'z' };
Console.WriteLine("Please enter your letters:");
// asdfojiaqweb;ounqwrb;ounwqen;zzzn bnaozonza
string sentence = Console.ReadLine().ToLower();
for (int i = 0; i < sentence.Length; i++)
{
if (letter.Contains(sentence[i]))
{
total++;
}
}
Console.WriteLine("Total number of Z uses is: {0}", total);
// Console.WriteLine(sentence.Substring(0, 1));
If you must use Substring, then replace your loop by this
for (int i = 0; i < sentence.Length; i++)
{
if (sentence.Substring(i, 1) == "z")
{
total++;
}
}
And if you need to both count uppercase and lowercase z, then use following code
for (int i = 0; i < sentence.Length; i++)
{
if (string.Equals(sentence.Substring(i, 1), "z", StringComparison.OrdinalIgnoreCase))
{
total++;
}
}

Peek() never evaluating to negative one

I'm learning C and C#, this question is for C#. I have this while loop and it is resulting in a infinite loop. I have used this before and it always worked great. But now it just loops forever and never exits. I'm doing this while loop to count the number of lines in the file.
Here is the code:
using (TextReader obj2 = new StreamReader(combined))
{
int count = 1;
while (obj2.Peek() != -1)
{
count++;
}
obj2.Close();
TextWriter obj = File.AppendText(combined);
Console.Write("How many lines do you want to add to the file?:");
int numberOfLines = 0;
int lineNumer = count + 1;
numberOfLines = Convert.ToInt32(Console.ReadLine());
for (int i = 0; i < numberOfLines; i++)
{
Console.Write("Enter a line of text:");
string line = Console.ReadLine();
obj.WriteLine(lineNumer + ". " + line);
}
}
Peek() doesn't advanced the reader. You need to make a call to obj2.Read() inside your loop, or it will never terminate as you've seen.
From the linked MSDN reference:
Reads the next character without changing the state of the reader or
the character source. Returns the next available character without
actually reading it from the reader.
See also Read() on MSDN.
These two methods work hand-in-hand quite often so that you can check if the stream has ended without affecting it. You're on the right track!

Categories