This week's book giveaway is in the Kotlin forum.
We're giving away four copies of Kotlin for Android App Development and have Peter Sommerhoff on-line!
See this thread for details.
Win a copy of Kotlin for Android App Development this week in the Kotlin 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
  • Liutauras Vilda
  • Devaka Cooray
  • Jeanne Boyarsky
  • Bear Bibeault
Sheriffs:
  • Junilu Lacar
  • Paul Clapham
  • Knute Snortum
Saloon Keepers:
  • Ron McLeod
  • Tim Moores
  • Stephan van Hulst
  • salvin francis
  • Carey Brown
Bartenders:
  • Tim Holloway
  • Frits Walraven
  • Ganesh Patekar

Help with variables, improperly assigning value or using Math.random wrong?  RSS feed

 
Greenhorn
Posts: 7
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Good morning JavaRanch!
In the following code, I'm trying to create a guessing game which will take user input to assign the range of numbers for the guessing game, create a random number to be the correct answer, and then will accept user input until that correct number, assigned as "computer" in the following code, is guessed. Right now I'm running into a slight issue with the variable "computer," which is most likely due to 1) me improperly using Math.random or 2) improperly assigning the value to computer and then calling it later. Can anyone help me fix my code so that computer is assigned as something other than 0? Thank you!



 
Marshal
Posts: 62881
203
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Welcome to the Ranch

Well, when you get to line 26, you haven't called the playGame() method, so you can expect to find a 0 there. But why are you putting that sort of debugging code in toString()? In fact most of that code belongs in different methods, not toString().
I don't like doing arithmetic with Math#random(); have a look at this old thread; I think random.nextInt() works better.
 
Collie Mason
Greenhorn
Posts: 7
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thank you! I called the playGame() method in toString(), and it cleared up my issue. However, now "computer" is only being assigned as 1, not somewhere in the range between 1 and the user's input (assigned as "upperBound"). How can I fix this?

I appreciate the suggestion with random.nextInt(), and I may use that in future code. This project is me trying to get experience with Math.random().
 
Bartender
Posts: 2212
47
Firefox Browser IntelliJ IDE Java Linux Spring
  • Likes 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

Collie Mason wrote:Thank you! I called the playGame() method in toString(), and it cleared up my issue. However, now "computer" is only being assigned as 1, not somewhere in the range between 1 and the user's input (assigned as "upperBound"). How can I fix this?

I appreciate the suggestion with random.nextInt(), and I may use that in future code.



And as it turns out Math.random() is the cause of your problem. Well, not the method itself, but it is very easy to put parentheses wrong when using it.

(int)Math.random() * ((upperBound) + 1) + 1

Math.random() returns a double greater than or equal to 0.0 and less than 1.0. When you convert such double to an int you always get 0.

0 * ((upperBound) + 1) + 1

Anything multiplied by 0 is 0.

0 + 1

Zero plus one equals one.

1
 
Sheriff
Posts: 12994
217
Android Debian Eclipse IDE IntelliJ IDE Java Linux Mac Spring Ubuntu
  • Likes 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

Campbell Ritchie wrote:But why are you putting that sort of debugging code in toString()? In fact most of that code belongs in different methods, not toString().


@OP: The question Campbell asked may not have registered on your radar but it alludes to one of the biggest problems you have in your code right now: Your toString() method contains logic that it shouldn't contain.

The toString() method's only responsibility is to return a String representation of the current object. Your toString() method does way more than just that. It contains the entire game loop (the logic that controls the flow of the game).

There are several aspects to your code that indicate confusion and lack of clarity on your part as to how all this works. That's Ok, all beginners go through this because you don't really know any better.

Consider this, for example:

This made me go, "What?!" when I first read it. The reason is that the name "response" is misleading. I would have thought that a response was something the user entered in response to being prompted by the program to enter a guess. That doesn't seem to be the case though since you assign the value of response to the upperBound field on line 13.  

Are you actually asking the user to enter the upper bound of the range of numbers that the computer will choose a random number from? Or is that really a pre-determined value like 100, for example, that you're using to initialize the game object?
 
Campbell Ritchie
Marshal
Posts: 62881
203
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

Collie Mason wrote:Thank you!

That' a pleasure

I called the playGame() method in toString(), and it cleared up my issue. . . .

I'm afraid it hasn't sorted out your issue; all it means is that you are getting a non‑zero result when you print it out. You want to be able to do something like:-Use toString() to return a (maybe very short [one line]) description of the state of the game.

I appreciate the suggestion with random.nextInt(), and I may use that in future code. This project is me trying to get experience with Math.random().

I know the Java™ Tutorials recommends that, but I think it is not‑quiite‑best code. If you go back to the link I gave you yesterday, you will see I said,

Putting the () in the wrong places around the cast will probably give you a pseudo‑random int between 0..0

And, as Paweł has explained, that is exactly what has happened. I am not quite sure about your arithmetic there; you appear to have + 1 twice. Work it out carefully assuming Math#random() returns 0.999999999 and your bounds are 0...20; I think there is a risk that your formula will return 1 until you get the () right, and then there is a risk of its evaluating to 21. The correct formula isNo it isn't. UseBoth those formulae give you a number in the range 1...upperBound inclusive. The commented‑out version gives you a range one too large; I shall let you work out which the “extra” potential result is.

Actually, if you are testing your app, don't start with plain simple Random(). UseGive the random object a “seed”; then you will always get the same sequence of numbers. When you have finished testing, delete the “seed” and you will get different sequences each time.

The + 1 part converts the numbers from the way computers usually count (0...n − 1) to how people count 1...n
 
Campbell Ritchie
Marshal
Posts: 62881
203
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

A few minutes ago, I wrote:. . . Both those formulae give you a number in the range 1...upperBound inclusive. . . .

But I have realised that isn't quite true. Challenge: work out the value/values of upperBound for which my second formula will fall down and not give you results in the required range. Assume that upperBound is a positive number. This isn't an easy question.
 
All of the world's problems can be solved in a garden - Geoff Lawton. Tiny ad:
RavenDB is an Open Source NoSQL Database that’s fully transactional (ACID) across your database
https://coderanch.com/t/704633/RavenDB-Open-Source-NoSQL-Database
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!