程序的COntrol不会进入for循环

时间:2011-07-15 12:47:31

标签: c#

我在这里粘贴代码:

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()
        {
            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();
            }
        }
    }   

}

3 个答案:

答案 0 :(得分:5)

您似乎在n中将getData()重新声明为本地变量。

尝试将该行更改为:

 n = Convert.ToInt32(Console.ReadLine());

即。删除int

答案 1 :(得分:1)

嗯......

因为您没有使用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();
        }
    }
}

我建议您使用this区分范围变量和实例变量!

答案 2 :(得分:0)

如果您尝试在getData()中使用Console.ReadLine()分配n,则需要删除之前的“int”。目前,您在不同的范围内有2个“n”变量。这就是你的循环不起作用的原因。