• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

I'm a freshman CS major and I was wondering if there was a better way to complete this assignment?

 
Greenhorn
Posts: 7
1
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
The assignment was:
You're going to read in a bunch of numbers and count how many times they fall into a specific range.  
Then, you will show this count using a histogram
for 10 ranges, each 10 numbers wide
For example, suppose the following numbers are given, and you had two ranges (0 - 4, 5 - 10)
3
7
4
1

You would output:

***
*


1. Download and add the histogram3.txt file attached to this assignment to your project
2. This file contains numbers in the range 1 - 100
3. Your goal is to make a 10-range histogram program, with each range being 10 numbers wide, using histogram3 as input
4. Create an array to hold the 10 counts.  Be sure to choose the correct type ...
5. Create a loop to read in each entry of histogram3 and increment the appropriate array entry based on the range the number falls into (1-10, 11-20, etc).  How you do this is up to you, though I recommend IF statements if you're stuck.
6. Generate a histogram using the array as the data, just like you did with the file data in the last assignment.

I attached a picture of the program I submitted for the assignment. I made a string array to hold the counts and then used if-else statements to assign each number from the file to an index in my array. I just feel like I could have simplified it a bit?
stackoverflow2.PNG
My code for the assignment
My code for the assignment
 
Marshal
Posts: 79151
377
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Welcome to the Ranch

That looks like the common way to create a histogram.
What did they say on SO?
I like the multiple if‑elses, but I prefer to avoid <= and >= if I can get away with < and >. That would mean reversing the direction of the block. I can't copy your code because it is in a Screenshot. I would however write something like this:-I think that is easier to read: all round numbers and no risk of confusion with equality.
 * * * * * * * * * *
Because the subranges are all the same length, you are in a corner case where you can simplify that by division:-Most histograms are made with ints, so you would avoid the +=.You still have the problem of creating the lines; repeated += is inefficient. Well, you won't notice the inefficiency until you get into thousands and thousands of operations, and it is much faster than it was before Java9, but you can try String#repeat(). Relatively new method your department might not be familiar with:-Or you can add that to a StringBuilder. Maybe slightly faster execution:-
 
Saloon Keeper
Posts: 27752
196
Android Eclipse IDE Tomcat Server Redhat Java Linux
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Welcome to the Ranch, Cam!

Two things, though. We would prefer that you not post screenshots. They often don't display well and are hard to read and they eat up a lot of storage space on our servers. Where possible, copy-and-paste actual text. Our "Code" tag button can be used to wrap markers around the source code (or XML or SQL or other pre-formatted text).

Also, it looks like you may have cross-posted this question to StackOverflow. As a courtesy, please tell people when you do that, since often a question is being answered 2 different ways in 2 different places and people both here are there (and those who visit both) can get very confused.

Thanks!
 
Saloon Keeper
Posts: 15484
363
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Welcome to CodeRanch!

We prefer it if you don't post screenshots of code. Instead, copy the code into your post and surround it with code tags, [code]like this[/code].

Anyway, you can simplify your current code by recognizing that your ranges have the same size and follow each other without gaps between the ranges. That means that instead of a ladder of if-else statements, you can apply a formula to your number to determine the index of the range you're looking for.

What formula can you think of that when you plug in any number between 1 and 10, yields 0? And yields 1 for any number between 11 and 20? And 7 for any number between 71 and 80?

Your code then becomes:

There are some other improvements that should be made to the code:

  • Use Files.newBufferedReader(Path) to access files, not the FileReader class.
  • Close your resources when you're done with them. You never close the histogram file. You can do this by using a try-with-resources statement.
  • Don't use Scanner.hasNext() if you're expecting an int. Use Scanner.hasNextInt() instead.
  • Don't repeatedly concatenate to a string inside a loop. Instead of using an array of String, use an array of StringBuilder.
  • When concatenating a single character, don't use a string literal ("*"), but use a character literal ('*') instead.
  • Don't use a for-loop with index to iterate through all elements of an array or collection. Instead, use the enhanced for-loop.
  • Don't put all your logic in the main method. The object oriented approach is to create a HistogramBuilder class that encapsulates your string builders. The main method should only create an instance of this class, tell it to read the numbers file, and tell it to print out the histogram:

  •  
    Campbell Ritchie
    Marshal
    Posts: 79151
    377
    • Mark post as helpful
    • send pies
      Number of slices to send:
      Optional 'thank-you' note:
    • Quote
    • Report post to moderator

    Stephan van Hulst wrote:. . . What formula can you think of that when you plug in any number between 1 and 10, yields 0? And yields 1 for any number between 11 and 20? And 7 for any number between 71 and 80?

    I think I have already told him that.

    . . .

  • Use Files.newBufferedReader(Path) to access files, not the FileReader class.
  • I hadn't noticed because I couldn't read the code You can also use ...new Scanner(Paths.get("/home/campbell/myNumbersFile"))... or similar.

  • Close your resources when you're done with them. You never close the histogram file. You can do this by using a try-with-resources statement.
  • Stephan did use try with resources, and you can read more about it in the Java™ Tutorials.

    . . . Don't repeatedly concatenate to a string inside a loop. Instead of using an array of String, use an array of StringBuilder.

    I had a different way to add the *s, which goes to show there are often several different ways to achieve the desired result. And sometime even several different good ways to do it!

    . . .

  • Don't use a for-loop with index to iterate through all elements of an array or collection. Instead, use the enhanced for-loop.
  • Another Java™ Tutorials section. The enhanced for loop (also called for‑each) is best if you are iterating the whole of a data structure in the normal (=forward) direction and in a read‑only fashion. Which you are doing here.

    [list]Don't put all your logic in the main method. The object oriented approach is to create a HistogramBuilder class that encapsulates your string builders. . . .

    I think Stephan would like you to complete the code where he threw the exceptions.
    I would recommend you handle any exceptions you expect to suffer rather than simply declaring them with throws.
    As Stephan says, this is procedural code, and I presume nobody has taught you object orientation yet.
     
    Campbell Ritchie
    Marshal
    Posts: 79151
    377
    • Mark post as helpful
    • send pies
      Number of slices to send:
      Optional 'thank-you' note:
    • Quote
    • Report post to moderator
    Work out how you can write a loop to populate the dots array. Is that better than the array initialiser or worse?
     
    Bartender
    Posts: 5465
    212
    • Mark post as helpful
    • send pies
      Number of slices to send:
      Optional 'thank-you' note:
    • Quote
    • Report post to moderator
    If you are on a recent java version, then an idea is to make a frequency count of the ranges, and then use "*".repeat. If you have a, say, TreeSet of the ranges, then it can be done in two lines of code.
     
    cam easterly
    Greenhorn
    Posts: 7
    1
    • Mark post as helpful
    • send pies
      Number of slices to send:
      Optional 'thank-you' note:
    • Quote
    • Report post to moderator

    Tim Holloway wrote:Welcome to the Ranch, Cam!

    Two things, though. We would prefer that you not post screenshots. They often don't display well and are hard to read and they eat up a lot of storage space on our servers. Where possible, copy-and-paste actual text. Our "Code" tag button can be used to wrap markers around the source code (or XML or SQL or other pre-formatted text).

    Also, it looks like you may have cross-posted this question to StackOverflow. As a courtesy, please tell people when you do that, since often a question is being answered 2 different ways in 2 different places and people both here are there (and those who visit both) can get very confused.

    Thanks!



    Ok sorry about that! I did try to post this on stack but I thought I never ended up posting it oops.
     
    Campbell Ritchie
    Marshal
    Posts: 79151
    377
    • Mark post as helpful
    • send pies
      Number of slices to send:
      Optional 'thank-you' note:
    • Quote
    • Report post to moderator
    Congratulations

    Because this thread which you started, appears in the February CodeRanch Journal, you are awarded a cow,
     
    What are you doing in my house? Get 'em tiny ad!
    a bit of art, as a gift, the permaculture playing cards
    https://gardener-gift.com
    reply
      Bookmark Topic Watch Topic
    • New Topic