• Post Reply Bookmark Topic Watch Topic
  • New Topic

How to generate the Random numbers at runtime  RSS feed

 
Debdeep Ganguly
Greenhorn
Posts: 16
Android IntelliJ IDE Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I have not been successful in running this code, it is showing NPE at the part where i add elements to a HashMap. I am also confused about how to generate the Random ID's during runtime. It is my beginner level so please feel free to sort out almost anything. Thanks.








The stack trace is:


 
Carey Brown
Bartender
Posts: 3011
46
Eclipse IDE Firefox Browser Java MySQL Database VI Editor Windows
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

Here you create a reference to a HashMap, but so far the reference hasn't been initialized to anything.
You'll want something like

or, better still

And 'o' is not a descriptive variable name.
 
Campbell Ritchie
Marshal
Posts: 55772
163
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
flag = 1 ???
You are writing Java┬« not C. You have a boolean type which you should use rather than messing around with 0=false and non‑0=true. Also flag is a very poor name for a flag variable; nobody knows what it means.
Why is that Map static? If you don't have a good reason to make something static, then it is a serious mistake.
Where are you using random numbers? The thread asks abut random numbers but I can't see any random numbers anywhere.
 
Debdeep Ganguly
Greenhorn
Posts: 16
Android IntelliJ IDE Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
@ Carrey Brown

Thanks for pointing me that silly one out.
I will try to be careful next time.

@ Campbell Ritchie

Thank you for highlighting my misconception. I am learning to code in Java now and this will really be in the top of list of my do's and don't's.
 
Knute Snortum
Sheriff
Posts: 4087
112
Chrome Eclipse IDE Java Postgres Database VI Editor
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I would make your instance variables private unless there is some good reason not to. For example:

Likewise, you should have access modifiers on your methods. I assume that menu() should be public and all the rest should be private.

Line 73, the variable r is never used.

Line 185, it looks like you have recursion that you really don't want. I would find a way to loop back to the top of the method rather than call it again. I'm also seeing that the methods you call from menu() call menu() again at the end. I would probably put a loop in menu() and have the other methods just return. All this will keep your stack memory cleaner.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!