for loop:string&号码没有继续添加&

时间:2014-12-15 16:51:01

标签: vb.net

我正在学习循环,我不能解决这个问题。

问题在以下代码中。

dim rt as integer = 2
dim i As Integer = 0
dim currentpg as string = "http://homepg.com/"


 For i = 0 To rt

currentpg = currentpg & "?pg=" & i

messagebox.show(currentpg)

next

'I hoped to get the following results

http://homepg.com/?pg=0
http://homepg.com/?pg=1
http://homepg.com/?pg=2

'but instead I'm getting this

http://homepg.com/?pg=0
http://homepg.com/?pg=0?pg=0
http://homepg.com/?pg=0?pg=0?pg=0

请帮帮我

谢谢。

2 个答案:

答案 0 :(得分:4)

你可能需要这样的东西:

Dim basepg as string = "http://homepg.com/"
For i = 0 To rt
  Dim currentpg As String = basepg & "?pg=" & i
  messagebox.show(currentpg)
Next

虽然正确的方法是将结果累积到List(Of String)中,然后在消息框中显示一次(或文本框/文件,如果结果太多)。你不想为每个网址错误用户(如果有100个网址会怎样?)。他们会厌倦点击OK。

答案 1 :(得分:0)

首先,在复制错误代码的输出时出错了。这是真实的。

http://homepg.com/?pg=0
http://homepg.com/?pg=0?pg=1
http://homepg.com/?pg=0?pg=1?pg=2

它不起作用,因为currentpg应该是常量,但每次迭代都会更改。 不要设置,只是得到。

MessageBox.Show(currentpg & "?pg=" & i)

或者您可以使用其他变量使其更具可读性。

Dim newpg As String = currentpg & "?pg=" & i
MessageBox.Show(newpg)

此外,您的代码效率低下。我建议你这样改变它。

Dim iterations As Integer = 2
Dim prefix As String = "http://homepg.com/?pg="
For index As Integer = 0 To iterations
    MessageBox.Show(prefix & index)
Next