• 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
  • Tim Cooke
  • Devaka Cooray
  • Ron McLeod
  • Jeanne Boyarsky
Sheriffs:
  • Liutauras Vilda
  • paul wheaton
  • Junilu Lacar
Saloon Keepers:
  • Tim Moores
  • Stephan van Hulst
  • Piet Souris
  • Carey Brown
  • Tim Holloway
Bartenders:
  • Martijn Verburg
  • Frits Walraven
  • Himai Minh

For loops problem

 
Ranch Hand
Posts: 36
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
This might be a simple question to you guys, but im having difficulties with this.
Why won't this for loop print out 1 to 31 as on dayInMonth array? but instead it only goes up to 12?



 
Bartender
Posts: 825
5
Python Ruby Java
  • Likes 1
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Your for loop is totally different from what you want. This code should produce ArrayIndexOutOfBoundsException after printing value 12.

What you want to do in for loop is initialize counter (say your x) to go from 0 to the last index value of an array (note that you can get length of an array with array.length). Then inside your loop you would access and print out value that is stored in the array at position (index) specified by x, not x + 1.

Also, please read UseCodeTags (<-click) and edit your post accordingly so the code will be easier to read.
And, welcome to the Ranch!
 
Terence hiu
Ranch Hand
Posts: 36
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Thank you for your help, I finally solved the problem.
Thank you very much!
 
Marshal
Posts: 76867
366
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
I have added code tags, and you can see how much better it looks. Why are you returning null? That is a potentially dangerous practice. That method ought to have void for its return type.
 
He repaced his skull with glass. So you can see his brain. Kinda like this tiny ad:
the value of filler advertising in 2021
https://coderanch.com/t/730886/filler-advertising
reply
    Bookmark Topic Watch Topic
  • New Topic