The COntrol of the program does not enter the for loop
Here i am pasting the code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace star1
{
class Program
{
static void Main(string[] args)
{
Myclass obj = new Myclass();
obj.getData();
obj.pattern();
}
}
class Myclass
{
int i, n, j;
public void getData()
{
开发者_StackOverflow中文版 Console.WriteLine("Program for displaying pattern of *.");
Console.Write("Enter the maximum number of *: ");
int n = Convert.ToInt32(Console.ReadLine());
}
public void pattern()
{
Console.WriteLine("\nPattern 1 - Left Aligned:\n");
for (i = 1; i <= n; i++) // The Control does not enter the for loop
{
for (j = 1; j <= i; j++)
Console.Write("*");
Console.WriteLine();
}
}
}
}
Looks like you're redeclaring n
as a local variable in getData()
.
Try changing that line to:
n = Convert.ToInt32(Console.ReadLine());
i.e. remove the int
.
well ...
as you are not using this
...
class Myclass
{
int i, n, j;
public void getData()
{
Console.WriteLine("Program for displaying pattern of *.");
Console.Write("Enter the maximum number of *: ");
this.n = Convert.ToInt32(Console.ReadLine());
// OR
//n = Convert.ToInt32(Console.ReadLine());
}
public void pattern()
{
Console.WriteLine("\nPattern 1 - Left Aligned:\n");
for (i = 1; i <= n; i++) // The Control does not enter the for loop
{
for (j = 1; j <= i; j++)
Console.Write("*");
Console.WriteLine();
}
}
}
i would encourage you to use this
to distinct between scope- and instance-variables!
If you try to assign n using Console.ReadLine() in getData(), you need to remove the "int" just before. Currently, you have 2 "n" variable in different scopes. That's why your loop doesn't work.
精彩评论