【问题标题】:Really struggling with sub procedures while making star drawing program在制作星星绘图程序时真的很挣扎子程序
【发布时间】:2014-12-10 22:21:02
【问题描述】:

我正在尝试创建一个绘制一系列空格和星号的子过程,然后输出结果。用户输入他们想要的星星数量和空间数量,然后输出在屏幕上绘制的星星和空间。例如,DrawStars(4,5) 将输出 ----*****。

到目前为止,这是我的代码:

Module Module1

Sub Main()
    Dim Spaces As Integer = 0
    Dim Stars As Integer = 0
    Dim TotalChars As Integer = 0

    Console.WriteLine("Enter the number of spaces you want to enter")
    Spaces = Console.ReadLine

    Console.WriteLine("Enter the number of stars you want to enter")
    Stars = Console.ReadLine

    TotalChars = Spaces + Stars

    DrawStars(Spaces, Stars, TotalChars)

    Console.WriteLine("")

    Console.ReadLine()
End Sub

Sub DrawStars(ByVal Spaces As Integer, ByVal Stars As Integer, ByVal TotalChars As Integer)
    Dim Output As String

    Do Until TotalChars = Stars + Spaces
        If Spaces > 0 The
            Output = Console.ReadLine
        Else
            Console.WriteLine("*")
        End If
    Loop

End Sub

结束模块

【问题讨论】:

  • 你需要 2 个 For 循环,一个用于空格数,一个用于星号,只需将它们添加到相同的输出变量中即可;它不需要totalchars

标签: vb.net visual-studio-2010 visual-studio visual-studio-2008


【解决方案1】:

最简单的情况是使用 this constructor overload 创建 2 个字符串:

Sub DrawStars(ByVal Spaces As Integer, ByVal Stars As Integer, ByVal TotalChars As Integer)
    Console.Write(new String(" "C, Spaces))
    Console.Write(new String("*"C, Stars))
End Sub

上述代码不受无效输入参数的保护。

【讨论】:

  • 我认为他希望他们在同一行
  • 问题是,代码需要有空格来帮助缩进创建图片,如果需要的话可以跨越多行
【解决方案2】:

你必须改变你的条件。根据MainTotalChars 已经是Stars + Spaces

Do Until TotalChars = Stars + Spaces  '<-- Already True!
    If Spaces > 0 The
        Output = Console.ReadLine
    Else
        Console.WriteLine("*")
    End If
Loop

你也没有增加TotalChars,所以让我们换成2个For循环,因为@dotnetom已经展示了一种创建带有空格和星号的字符串的简单方法。

For i As Integer = 1 To Spaces
    Console.Write(" ")
Next
For i As Integer = 1 To Stars
    Console.Write("*")
Next

这不应该是一种复制和粘贴解决方案。这更像是一个示例,以及我在您的代码中看到的问题 =)

【讨论】:

  • 那么有没有办法让用户轻松进入下一行并继续前进,像图片一样创作?
  • @JeffCottonBWFC 添加另一个参数来指示要重复的行数
  • @JeffCottonBWFC 根据您提供的问题和代码,我真的不知道您期望什么样的输出。您有一个完全未使用的 Output 变量,而 Spaces 始终是 &gt; 0
  • 我试图在用户输入行数和星数后获取创建图片的代码。我必须获得在屏幕上绘制图像的程序,但我似乎无法使用代码来做到这一点
  • 如果你的意思是你想要在其中任何一个之后换行,只需在任一答案中添加Console.WriteLine()....问题询问 空格 而星号不是 线条和星星
猜你喜欢
  • 2015-12-22
  • 1970-01-01
  • 1970-01-01
  • 2022-06-15
  • 1970-01-01
  • 2013-09-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多