This week's book giveaways are in the Jython/Python and Object-Oriented programming forums.
We're giving away four copies each of Machine Learning for Business: Using Amazon SageMaker and Jupyter and Object Design Style Guide and have the authors on-line!
See this thread and this one for details.
Win a copy of Machine Learning for Business: Using Amazon SageMaker and JupyterE this week in the Jython/Python forum
or Object Design Style Guide in the Object-Oriented programming forum!
  • 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 all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Bear Bibeault
  • Paul Clapham
  • Jeanne Boyarsky
  • Knute Snortum
Sheriffs:
  • Liutauras Vilda
  • Tim Cooke
  • Junilu Lacar
Saloon Keepers:
  • Ron McLeod
  • Stephan van Hulst
  • Tim Moores
  • Tim Holloway
  • Carey Brown
Bartenders:
  • Joe Ess
  • salvin francis
  • fred rosenberger

Pretty confused with string arrays

 
Greenhorn
Posts: 16
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I am reading a book "Head First Java" and page 16 states:



so i tried to replicate this so i can make sure i understand it and did it like this in my own way:



what i am hoping the code does is to suggest a random combination for ice-cream flavour and toppings

now the error i receive when i run the (idk if it compiles is it now called a script?) code this is the error i receive :



Any thoughts appreciated.
 
Tatenda Mawoneke
Greenhorn
Posts: 16
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Update:

so i notice when i run the code it works sometimes but sometimes it doesnt:

 
Marshal
Posts: 67533
257
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You are using the same size calculation for the second and third arrays. The numbers got by adding the two arrays together will be out of bounds. This error will only happen sometimes because it is “random”. Don't try to calculate or record lengths of arrays: use myArray.length.
Please note the conventions HFJ uses for variableNames. No underscores please. Capitalise middleWordsInNames.
If you look here, you will find I don't like arithmetic with Math#random().If you go through the documentation for Random#nextInt(int), you will find the possible results will exactly fit the size of the array.
 
Rancher
Posts: 4453
47
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
num_of_Toppings is the total of one and two (7 in this case).
Consequently when you use it to generate the index to use for the arrays it has a pretty high chance of producing a number that's too large.
 
Tatenda Mawoneke
Greenhorn
Posts: 16
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

Dave Tolls wrote:num_of_Toppings is the total of one and two (7 in this case).
Consequently when you use it to generate the index to use for the arrays it has a pretty high chance of producing a number that's too large.



Ok i see the mistake thanks for your help!

have edited the code and this works fine :

 
Campbell Ritchie
Marshal
Posts: 67533
257
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Delete lines 9‑12. Use the .length fields throughout, or array1.length + array2.length for the total.
 
Tatenda Mawoneke
Greenhorn
Posts: 16
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

Campbell Ritchie wrote:Delete lines 9‑12. Use the .length fields throughout, or array1.length + array2.length for the total.



Thank you for your suggestion it really trimmed out the code and made it simpler. Also just added a little more touches to improve.



 
Tatenda Mawoneke
Greenhorn
Posts: 16
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
1 thing i am unsure of is the ones like this line:



what is really going on here: the "(int)(Math.random()" in particular what is that and why is it multiplied by the total number of items in the Icecream_flavour array? How does this produce a random number for the Icecream_flavour array
 
Dave Tolls
Rancher
Posts: 4453
47
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Math.random() returns a double between 0.0 and 1.0.
Multiple that by you number of things, and cast to an int (which strips the decimal part) and you get a number between 0 and numberOfThings - 1.
 
Campbell Ritchie
Marshal
Posts: 67533
257
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You have managed to indent the code well but some of your lines are too long.
The following won't get universal agreement; in fact it might get disagreement. I think you will reduce the risk of errors if you declare as few variables as you can. This is what you started off with:-And this is my corrupted version:-I have broken the longer lines and tried to get them to align so you can see in the output that you have the same array name twice in each of lines 16, 18, and 20. You would probably have done a better job breaking the lines when you wrote the code. If you are doing arithmetic with + in the same line as String concatenation, put () round the arithmetic. You haven't got a problem at present, but try this sort of line:-I haven't changed the claculation of your “random” numbers.
 
Sheriff
Posts: 14764
245
Mac Android IntelliJ IDE Eclipse IDE Spring Debian Java Ubuntu Linux
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Math.random() generates a pseudorandom number N such that 0 <= N < 1.0.  If you multiply it by a number U (for upper bound), then you have 0 * U <= N * U < 1 * U which you can simplify to 0 <= N * U < U. And as Dave mentioned above, the number generated is a double so you have to cast to an int to get the integer part of that number so it can be used as an index into an array.

Basically, it's the formula to generate a pseudorandom number that is greater than or equal to 0 and less than whatever is your upper bound which in your case is the array length.

An easier way to do this and the one we usually recommend is to use java.util.Random.nextInt(int upperBound) instead:


[Edit: Beaten to the punch not once, but twice! Oh, well]
 
Junilu Lacar
Sheriff
Posts: 14764
245
Mac Android IntelliJ IDE Eclipse IDE Spring Debian Java Ubuntu Linux
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
If you really want to trim down the code, you would remove more duplication. The duplicated idea you have is that of choosing a random element from an array. All those variables and temporary assignments would be unnecessary if you extract that idea to its own method, like so:

Then all you'd have to do in your main code is this:
 
Tatenda Mawoneke
Greenhorn
Posts: 16
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

Campbell Ritchie wrote:. . . This is what you started off with:- . . .And this is my corrupted version:- . . . If you are doing arithmetic with + in the same line as String concatenation, put () round the arithmetic. . . . .



This reduction is nice i understood it thanks, implemented it too:



What i did not really get was the "String concatenation" part...are you saying when adding two strings put them in brackets like so:

 
Campbell Ritchie
Marshal
Posts: 67533
257
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Please only quote the relevant parts of an old post, otherwise you are simply adding duplication.

The () need to surround the + and both its operands. It is sometimes necessary to use () in different places to maintain precedences. Did you try adding "There are" + to the beginning of your print instruction, as I suggested? With and without ()? What happened?
 
Don't MAKE me come back there with this tiny ad:
Java file APIs (DOC, XLS, PDF, and many more)
https://products.aspose.com/total/java
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!