• 0

Visual Basic - Making 1000 = "*"


Question

Need help making every 1000 = "*"

attach is what the final result should look like
This is my code:

Public Class Form1
 
    Private Sub btnShow_Click(sender As Object, e As EventArgs) Handles btnShow.Click
 
        'Number of planets before Pluto was "let go"'
        Const intNUM_PLANETS As Integer = 9
 
        'Planet names'
        Dim strArrayPlanetNames() As String =
        {"Mercury", "Venus", "Earth", "Mars", "Jupiter", "Saturn", "Uranus", "Neptune", "Pluto"}
 
        'diameter of each planet in miles'
        Dim dblArrayPlanetSizes() As Double =
        {3031, 7521, 7926, 4223, 88846, 74898, 31763, 30800, 1430}
 
 
        For intX = 0 To intNUM_PLANETS - 1
 
            'output name and size'
            lstPlanets.Items.Add(strArrayPlanetNames(intX) & "      " & dblArrayPlanetSizes(intX))
 
            'output bar chart on next line'
        Next
        
    End Sub

post-503111-0-56641300-1376880908.png

Link to comment
https://www.neowin.net/forum/topic/1171589-visual-basic-making-1000/
Share on other sites

15 answers to this question

Recommended Posts

  • 0

ermm is it something like this? this does not work but like what code should i add inside the lstPlanets.items.add(.....)

Option Strict On
Option Explicit On
'Anthony L
'CS 115
'Summer 2013
 Private Sub btnShow_Click(sender As Object, e As EventArgs) Handles btnShow.Click
 
        'Number of planets before Pluto was "let go"'
        Const intNUM_PLANETS As Integer = 9
 
        'Planet names'
        Dim strArrayPlanetNames() As String =
        {"Mercury", "Venus", "Earth", "Mars", "Jupiter", "Saturn", "Uranus", "Neptune", "Pluto"}
 
        'diameter of each planet in miles'
        Dim dblArrayPlanetSizes() As Double =
        {3031, 7521, 7926, 4223, 88846, 74898, 31763, 30800, 1430}
        Dim stars = New String("*"c, 1) 'stars = "*****"
 
        For intX = 0 To intNUM_PLANETS - 1
 
            'output name and size'
            lstPlanets.Items.Add(strArrayPlanetNames(intX) & "      " & dblArrayPlanetSizes(intX))
            lstPlanets.Items.Add(stars)
        Next
 
 
    End Sub
  • 0

Note: psuedo code below:

Const intNUM_PLANETS As Integer = 9

Dim strArrayPlanetNames() As String =
   {"Mercury", "Venus", "Earth", "Mars", "Jupiter", "Saturn", "Uranus", "Neptune", "Pluto"}
Dim dblArrayPlanetSizes() As Double =
   {3031, 7521, 7926, 4223, 88846, 74898, 31763, 30800, 1430}
 
For intX = 0 To intNUM_PLANETS - 1
   lstPlanets.Items.Add(strArrayPlanetNames(intX) & "      " & dblArrayPlanetSizes(intX))
  
   Dim numberOfStars As ??? = dblArrayPlanetSizes(intX))/1000   //??? - select variable type without decimal places
   for intY = 0 To numberOfStars
      lstPlanets.Items.Add("*")
   Next

Next
  • 0
Take the time to think about your problem, the data you have and in which form it is available. There's no point trying to get code examples to paste into your assignment if you don't understand how to reason about solving your problem. The code I gave you was not meant to be pasted verbatim into your assignment, but simply to illustrate how to create a string containing a repeating character.

 

Here's your problem in words:

For every planet you need to print its name and a certain amount of stars that corresponds to its size divided by 1000 and rounded up.

 

The planet names are in the array strArrayPlanetNames. The sizes are in the array dblArrayPlanetSizes.

 

For each planet, you'll first need to get its name and size from these arrays. Printing the name is easy. Printing the stars consists in

  1. finding the number of stars to print (i.e. the size divided by 1000 and rounded up)
  2. creating a string containing that many stars (I've showed you how already)
  3. printing that string to the output
 

From there it's only a matter of language syntax. Do you not understand what is an array, or how to get an element from an array? Or how to perform a division? Do you not understand what a for loop is? It's not clear where exactly lies the source of your confusion.

  • Like 1
  • 0

The best way to learn is by troubleshooting. Come up with a flowchart first, then write pseudo code for each block. This will makes things a lot clearer when writing code (at first).

 

If you just copy someone else's code, you will forget it after a few minutes.

  • 0

Yeah that's true but i do not learn a lot since this is an online class and the teacher never teach us or told us to read page something so i always google and read by myself which is kinda hard for me and there are several things that i have not learn maybe? or not? and yes it's very hard for me to know these codes... and btw 68k i tried using your code but then it multiply a lot of times and i do not really get the term of IntY = 0 so do we like start from the first number or?

this is what i have so far:

For intX = 0 To intNUM_PLANETS - 1
 
                'output name and size'
                lstPlanets.Items.Add(strArrayPlanetNames(intX) & "      " & dblArrayPlanetSizes(intX))
            Dim numberOfStars As Double = dblArrayPlanetSizes(CInt((intX) / 1000))
            For intY = 0 To numberOfStars
                lstPlanets.Items.Add("*")
            Next
 
        Next
  • 0

Yeah that's true but i do not learn a lot since this is an online class and the teacher never teach us or told us to read page something so i always google and read by myself which is kinda hard for me and there are several things that i have not learn maybe? or not? and yes it's very hard for me to know these codes... and btw 68k i tried using your code but then it multiply a lot of times and i do not really get the term of IntY = 0 so do we like start from the first number or?

this is what i have so far:

For intX = 0 To intNUM_PLANETS - 1

 

                'output name and size'

                lstPlanets.Items.Add(strArrayPlanetNames(intX) & "      " & dblArrayPlanetSizes(intX))

            Dim numberOfStars As Double = dblArrayPlanetSizes(CInt((intX) / 1000))

            For intY = 0 To numberOfStars

                lstPlanets.Items.Add("*")

            Next

 

        Next

What is CInt((intX) / 1000) supposed to be? It's the array index divided by 1000 and converted to an integer - which it already is. The value of this expression will always be 0. This doesn't make sense. You're not thinking about what your values represent.

 

Then you create a variable named numberOfStars which you assign to one of the values of dblArrayPlanetSizes array. This doesn't make sense: this array contains planet sizes. If you take an element from it, this element is a planet size, not a number of stars.

 

Also, you don't want to add each star as a separate list item; this will add each star on its own line. Create the string as I showed you and then add it as a single item to the list.

 

You want to 1) get the planet size from the array, 2) divide that size by 1000; 3) use the result of that division as the number of stars to create your string.

 

That's three sub-problems to solve. You know how to solve each of these individually; every one is just a single basic of code. Here are some hints (replace the comments with your code):

 

Dim planetSize = '... get the size from the array'
Dim numberOfStars = '... divide that size by 1000 and round up'
Dim stars = New String("*"C,  '... use the calculated number of stars to specify how many stars to put'
lstPlanet.Items.Add('... add that string the output'

By the way please use code tags when you post code.

  • 0

+Asik

I manage to get it working but is there another way to round this up?

 
               lstPlanets.Items.Add(strArrayPlanetNames(intX) & "      " & dblArrayPlanetSizes(intX))
            Dim numberOfStars As Double = Math.Round(dblArrayPlanetSizes(intX) / 1000) '... divide that size by 1000 and round up'
            Dim stars = New String("*"c, CInt(numberOfStars))  '... use the calculated number of stars to specify how many stars to put'
            lstPlanets.Items.Add(stars + "*") '... add that string the output'
  • 0

... why would you create a new duplicate array containing the planet sizes? How could you then divide that array by 1000? That wouldn't even compile.

 

The snippet I gave you goes inside your for loop. Use the loop index variable to access the existing planet size array you have, and retrieve a single planet size at a time.

 

By the way, the code you post often doesn't even compile. If you're working inside an IDE like Visual Studio, you should see red squiggles under the problematic lines and errors listed below. You don't need people on a forum to tell you your code doesn't work when Visual Studio already tells you that. Always make sure your code compiles and runs before anything else.

  • 0

 

Yeah that's true but i do not learn a lot since this is an online class and the teacher never teach us or told us to read page something so i always google and read by myself which is kinda hard for me and there are several things that i have not learn maybe? or not? and yes it's very hard for me to know these codes... and btw 68k i tried using your code but then it multiply a lot of times and i do not really get the term of IntY = 0 so do we like start from the first number or?

this is what i have so far:

For intX = 0 To intNUM_PLANETS - 1
 
                'output name and size'
                lstPlanets.Items.Add(strArrayPlanetNames(intX) & "      " & dblArrayPlanetSizes(intX))
            Dim numberOfStars As Double = dblArrayPlanetSizes(CInt((intX) / 1000))
            For intY = 0 To numberOfStars
                lstPlanets.Items.Add("*")
            Next
 
        Next

 

From http://msdn.microsoft.com/en-us/library/vstudio/5z06z1kb.aspx:

 

You use a For...Next structure when you want to repeat a set of statements a set number of times.

In the following example, the index variable starts with a value of 1 and is incremented with each iteration of the loop, ending after the value of index reaches 5.

For index As Integer = 1 To 5
    Debug.Write(index.ToString & " ")
Next
Debug.WriteLine("")
' Output: 1 2 3 4 5

Every time the For loop is initiated the variable "index" would be reset to "1".

  • 0

i tried it and it work well :|

Why are you surprised? IMO the method you're following doesn't seem to teach you the fundamentals right; you don't really understand what you're doing and just rushing through exercices. You'll hit a wall pretty soon at that rate. Get a good book and read it carefully. Learn to:

 

 - understand compiler error messages and how to find information about them

 - step through your code in the debugger so you can visualize what your program is doing at every statement

 

With good foundations you shouldn't need to ask people to guide you every step of the way, and then wonder how the program ended up working. Unfortunately, many courses are just plain bad, so you need to get additional resources by yourself. When I learned C++ I bought myself a huge tutorial book and read it on the bus; the material shown in class and exercices was insufficient by far.

This topic is now closed to further replies.
  • Recently Browsing   0 members

    • No registered users viewing this page.
  • Posts

    • Oddly, there was a time that UFC games were culturally relevant, largely because of the graphics and gameplay that was different than the norm. But it seems like as the sport grew in popularity, gaming outlets stopped talking about the games.
    • Microsoft Edge 149.0.4022.69 by Razvan Serea Microsoft Edge is a super fast and secure web browser from Microsoft. It works on almost any device, including PCs, iPhones and Androids. It keeps you safe online, protects your privacy, and lets you browse the web quickly. You can even use it on all your devices and keep your browsing history and favorites synced up. Built on the same technology as Chrome, Microsoft Edge has additional built-in features like Startup boost and Sleeping tabs, which boost your browsing experience with world class performance and speed that are optimized to work best with Windows. Microsoft Edge security and privacy features such as Microsoft Defender SmartScreen, Password Monitor, InPrivate search, and Kids Mode help keep you and your loved ones protected and secure online. Microsoft Edge has features to keep both you and your family protected. Enable content filters and access activity reports with your Microsoft Family Safety account and experience a kid-friendly web with Kids Mode. The new Microsoft Edge is now compatible with your favorite extensions, so it’s easy to personalize your browsing experience. Microsoft Edge 149.0.4022.69 changelog: Fixed an issue that caused the Downloads dialog to continue displaying the "Keep/Delete" prompt for .rdp files after the download completed. Stable channel security updates are listed here. Download: Microsoft Edge (64-bit) | 193.0 MB (Freeware) Download: Microsoft Edge (32-bit) | 170.0 MB Download: Microsoft Edge (ARM64) | 188.0 MB View: Microsoft Edge Website | Release History Get alerted to all of our Software updates on Twitter at @NeowinSoftware
    • Save 44% on Intuit QuickBooks Desktop Pro Plus 2024 (1 User for 1-Year) by Steven Parker Today's highlighted deal comes via our Apps + Software section of the Neowin Deals store, where for only a limited time, you can save 44% on Intuit QuickBooks Desktop Pro Plus 2024 (1 User + 1 Year) for Windows. Take control of your business finances with Intuit® QuickBooks® Desktop Pro Plus 2024 Lifetime Activation for Windows. This powerful accounting software simplifies bookkeeping, expense tracking, invoicing, and financial management—all in one intuitive platform. Designed for small business owners, freelancers, and accountants, QuickBooks® Desktop Pro Plus 2024 ensures accuracy, efficiency, and seamless transaction tracking. Stay organized, save time, and manage your finances with confidence—no subscriptions, just lifetime access! Financial and business management Comprehensive Financial Management: Gain access to a full suite of features designed to handle everything from creating invoices & managing expenses to generating reports and tracking sales. Enhanced Reporting Tools: Generate professional reports & insights to make informed financial decisions and help you stay ahead of your business goals. Job Costing: Track the profitability of specific jobs or projects. Fixed Asset Management: Track the depreciation & value of fixed assets. Customer & Vendor Management: Organize information, streamline communication & enhance customer relations. Sales Order Processing: Create & manage sales orders from start to finish. Purchase Order Processing: Create & manage purchase orders to streamline vendor payments. Improved Inventory Management: Enhanced features for tracking inventory levels & costs. Automation, integration, and support Enhanced Bank Feeds: Web Connect (manual QBO imports), works on all licenses for easier bank reconciliation Time Tracking: Track employee time to accurately calculate payroll and project costs Easy Data Import: Quickly transfer financial data from Excel or older QuickBooks® versions Why choose Intuit® QuickBooks® Desktop Pro Plus 2024? Effortless Installation: Quick and easy setup with step-by-step guidance. No Hidden Costs: One-time payment—no subscriptions or recurring fees. Direct Official Download: Access the software securely from the official QuickBooks® website. Stay Up to Date: Get the latest updates and features for optimal performance. Multilingual Support: Available in multiple languages to suit your needs. Lifetime Access: A one-time purchase means no ongoing costs. IMPORTANT: Cloud integrations (QuickBooks Payments, TurboTax, and Online logins) are NOT included. Good to know: Length of access: lifetime Redemption deadline: redeem your code within 30 days of purchase Access options: Windows Max number of device(s): 2 (for 1 user only and can't be used simultaneously) Version: 2024 (United States) 64-bit Available to both NEW and EXISTING users For US customers only Updates included An Intuit QuickBooks Desktop Pro Plus 2024 (1 User + 1-Year) for Windows: Lifetime License normally costs $536, but it can be yours for just $299.99 for a limited time, a saving of $236. There are also other plans available. For specifications, and license info please click the link below. Get Intuit QuickBooks Desktop Pro Plus 2024 for just $299.99 This is a time limited deal For US customers only. Support queries If you have queries or need support for any of the Neowin Deals, please use the contact form here. Neowin Deals are managed and sold by StackCommerce who represent Neowin on an affiliate basis. Why we post these deals We post these because we earn commission on each sale so as not to rely solely on advertising, which many of our readers block. It all helps toward paying staff reporters, servers and hosting costs. So for those that keep moaning and complaining, be thankful we're still online for you to even do that. Other ways to support Neowin Whitelist Neowin by not blocking our ads Create a free member account to see fewer ads Make a donation to support our day to day running costs Subscribe to Neowin - for $14 a year, or $28 a year for an ad-free experience Disclosure: Neowin benefits from revenue of each sale made through our branded deals site powered by StackCommerce.
    • AFAIK you shouldn't be getting a consent popup at all from Canada, so I think it is to do with a VPN or private/secure DNS.
    • From what I see it's only for Insider - preview builds. Not for everybody. So...
  • Recent Achievements

    • Week One Done
      agatameier earned a badge
      Week One Done
    • One Month Later
      agatameier earned a badge
      One Month Later
    • Week One Done
      ssd21345 earned a badge
      Week One Done
    • Contributor
      MarkHughes4096 went up a rank
      Contributor
    • Dedicated
      jordanspringer earned a badge
      Dedicated
  • Popular Contributors

    1. 1
      +primortal
      507
    2. 2
      +Edouard
      175
    3. 3
      PsYcHoKiLLa
      139
    4. 4
      ATLien_0
      90
    5. 5
      Steven P.
      76
  • Tell a friend

    Love Neowin? Tell a friend!